找到所有对号那笔高达S [英] Find all pair of nos that sum up to S

查看:191
本文介绍了找到所有对号那笔高达S的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数组,找到所有对号的总结给定值。 有保持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 */

这篇关于找到所有对号那笔高达S的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆