找到所有对号那笔高达S对号

2023-09-11 00:29:10 作者:爺.就是這麽拽

给定一个数组,找到所有对号的总结给定值。 有保持2指针在正面和背面,并使他们更加接近找到一对经典的O(n)的算法。这只会导致1对。如果你希望所有对。 奖励:找到的最小距离对

您可以做到这一点为O(n)。

解决方案

  INT ARR [SIZE] / *按升序排序* /

 诠释A = 0,B =大小 -  1,mindist = -1,总和;
 而(A< B){
    总和= ARR [α] +改编并[b];
    如果(总和== TARGET){report_pair(A,B); mindist = B  -  A; A ++}
    否则,如果(总和<目标)A ++;
    其他b--;
 }

 / *最小距离储存在mindist * /
 

高达模型上色用马克笔怎么样 还要不要上底漆

Given an array, find all pair of nos that sum up to a given value. There is the classic O(n) algorithm of keeping 2 pointers at the front and back and bringing them closer to find the pair. This only leads to 1 pair. What if you want all pairs. Bonus: Find the minimum distance pair.

Can you do this in O(n).

解决方案

 int arr[SIZE]; /* sorted in ascending order */

 int a = 0, b = SIZE - 1, mindist = -1, sum;
 while (a < b) {
    sum = arr[a] + arr[b];
    if (sum == TARGET) { report_pair(a, b); mindist = b - a; a++ }
    else if (sum < TARGET) a++;
    else b--;
 }

 /* minimum distance stored in mindist */