[英]Sorted array and finding sum with complexity O(n)
We have sorted array arr[]={2,4,5,7,8,12,16,18,20}
. 我们对数组arr[]={2,4,5,7,8,12,16,18,20}
进行了排序。
We need to find out pair of elements whose addition is 12
, with complexity O(n)
. 我们需要找出加法为12
的元素对,其复杂度为O(n)
。
Could anyone help on it? 有人可以帮忙吗?
No solution for you unfortunately, just some things to think about that should lead you in the right direction: 不幸的是,没有适合您的解决方案,只需考虑一些事情即可引导您朝正确的方向前进:
Keeping in mind that the array is sorted, which of the following are true? 请记住,数组已排序,以下哪项是正确的?
arr[x+1] + arr[y] < arr[x] + arr[y]
or arr[x+1] + arr[y] > arr[x] + arr[y]
arr[x] + arr[y-1] < arr[x] + arr[y]
or arr[x] + arr[y-1] > arr[x] + arr[y]
If you think about the answers to these long enough (and maybe draw it), a solution should follow. 如果您考虑这些问题的答案足够长的时间(并可能画出答案),那么应该采取解决方案。
Hint for how to start: 提示如何开始:
Let x = 0, y = n-1. 令x = 0,y = n-1。
... ...
Try this: 尝试这个:
Since the array is sorted, take the sum of the first element (arr[0]) and the last element(arr[8]). 由于数组已排序,因此取第一个元素(arr [0])和最后一个元素(arr [8])之和。 If the sum is greater than 12, then we need to lower the sum, so we replace the largest number by the next largest number(in this case, arr[7]); 如果总和大于12,则需要降低总和,因此我们用下一个最大数替换最大数(在这种情况下,为arr [7]); If the sum is less than 12, we need to increase the sum, so we replace the smallest number by the next smallest number, (in this case, replace arr[0] with arr[1]). 如果总和小于12,则需要增加总和,因此我们用下一个最小数替换最小数(在这种情况下,用arr [1]替换arr [0])。 Keep repeating this process until you get the sum you want or the two numbers you are summing up is from the same index in the array. 继续重复此过程,直到获得所需的总和或要求和的两个数字都来自数组中的同一索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.