发现一对整数的有序数组到K其中总和 [英] finding a pair of integers in a sorted array which sum to K

查看:165
本文介绍了发现一对整数的有序数组到K其中总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于整数有序数组,怎样才能找到一对整型总和的k?

Given a sorted array of integers, how can we find a pair of integers that sum to K?

例如。 阵列= 1,3,5,6,0 K = 6 ,答案是1和5

e.g. array = 1,3,5,6,0, K = 6, the answer is 1 and 5.

时间复杂度应尽量减少。

Time complexity should be minimized.

推荐答案

您可能会想看看这篇博客文章:

You may want to look at this blog post:

<一个href="http://www.codingatwork.com/2011/07/array-sum/">http://www.codingatwork.com/2011/07/array-sum/

我的做法是做一个列表的二进制搜索 K / 2 ,然后步行一个变量 A 左,另一个变量 B 右键试图找到一个解决办法 A + B = K

My approach would be to do a binary search of the list for K/2, then walk one variable a left and another variable b right trying to find a solution a+b=K.

这个想法是启动 A 在数量最多的小于或等于 K / 2 和启动 B 在最小数大于 A 。此外,使用二进制搜索找到 A B 是数组中的下一个元素。然后

The idea would be to start a at the largest number less than or equal to K/2 and start b at the smallest number greater than a. Again, use a binary search to find a and let b be the next element in the array. Then

  • 如果 A + B = K ,然后收益率(A,B)
  • 如果 A + B&LT;氏/ code>,然后移动 B 向右移动一个位置。
  • 如果 A + B&GT;氏/ code>,然后移动 A 到左边一个位置。
  • If a+b = K, then return (a,b).
  • If a+b < K, then move b to the right one position.
  • If a+b > K, then move a to the left one position.

当然,你可以跳过二进制搜索,马上开始 A 在数组的开头和 B 在数组的末尾,然后执行

Of course, you can skip the binary search and just start a at the beginning of the array and b at the end of the array, and then do

  • 如果 A + B = K ,然后收益率(A,B)
  • 如果 A + B&LT;氏/ code>,然后移动 A 向右移动一个位置。
  • 如果 A + B&GT;氏/ code>,然后移动 B 到左边一个位置。
  • If a+b = K, then return (a,b).
  • If a+b < K, then move a to the right one position.
  • If a+b > K, then move b to the left one position.

这是可能更快。

这篇关于发现一对整数的有序数组到K其中总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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