简体   繁体   English

排序数组并找到复杂度为O(n)的和

[英]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.

相关问题 在 O(log n) 时间复杂度中查找排序数组的总和 - Finding sum of a sorted array in O(log n) Time Complexity 以O(log n)复杂度计算排序数组中值的出现次数 - Count the number of appearances of a value in a sorted array in O(log n) complexity 查找特定的缺失数组元素:O(n + k)复杂度 - Finding a Particular Missing Array Element: O(n+k) Complexity 在排序数组中查找插入点的速度比O(n)还快? - Finding insertion points in a sorted array faster than O(n)? 在数组中查找不同值的O(1)空间复杂度的O(N ^ 2)时间复杂度 - Alternative O(N^2) time complexity with O(1) space complexity for finding distinct values in array 如何在不改变原始数组的情况下从时间复杂度为 O(n) 或更好的排序数组中获取唯一值 - How to get unique values from a sorted array with time complexity of O(n) or better without altering the original array 排序数组中N次插入操作的时间复杂度 - Time complexity for N insert operations in a sorted array 如何以大O(N)的时间复杂度对循环中的数组部分求和 - How to Sum array parts within a loop with time-complexity of Big O(N) 如何在 O(n) 时间复杂度中找到总和等于特定数字的连续子数组 - How to find continuous sub-array whose sum is equal to a particular number in O(n) time complexity 如何使用包含负整数的数组在 O(n) 时间复杂度中用 python 解决两个求和问题 - how to solve two sum problem with python in O(n) time complexity with an array that include negative integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM