码迷,mamicode.com
首页 > 编程语言 > 详细

算法:找出有序数组中两数,它俩之和等于输入值

时间:2016-08-14 10:20:36      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

题目:已知按序排列的整数数组,输入任意数number,当数组中某两数之和等于number时,打印出两个数。

要求:复杂度为o(n)

解法:

数组已是有序排列,且两个加数一定满足条件:较小加数<= (number/2) <= 较大加数;那么只需要找出该数组的较小加数和较大加数分界index,以该分界为起点分别往左右两边逐个取值匹配。

若两数之和>number,说明较小加数还要再小,向数组的较小值方向移位取值与原较大值重新匹配。

若两数之和<number,说明较大加数还要再大,向数组的较大值方向移位取值与原较小值重新匹配。

 

 1 public void seachAdden(int number, int[] arry) {
 2         int midIndex = 0; // 较大加数和较小加数的分界(数组下标)
 3         boolean result = false;
 4         for (int i = 0; i < arry.length; i++) { // 定位midIndex的值
 5             if (arry[i] > (number / 2)) {
 6                 midIndex = i - 1; // 如果数组的第一个数就已经大于用户输入的数字,则midIndex为-1
 7                 break;
 8             }
 9         }
10         if (midIndex != -1) {
11             int smallerIndex = midIndex; // 记录较小加数在数组中的下标
12             int biggerIndex = midIndex + 1; // 记录较大加数在数组中的下标
13             do {// 开始匹配
14                 if (arry[smallerIndex] + arry[biggerIndex] > number) {
15                     smallerIndex--;
16                 } else if (arry[smallerIndex] + arry[biggerIndex] < number) {
17                     biggerIndex++;
18                 } else {
19                     // 匹配成功
20                     System.out.println("arry[" + smallerIndex + "] 和 arry[" + biggerIndex
21                             + "] 匹配,即  " + arry[smallerIndex] + " + " + arry[biggerIndex]
22                             + " = " + number);
23                     result = true;
24                     smallerIndex--;
25                     biggerIndex++;
26                 }
27             } while ((smallerIndex >= 0) && (biggerIndex <= arry.length - 1));
28         }
29         if (result == false) {
30             System.out.println("无匹配");
31         }
32     }

 

算法:找出有序数组中两数,它俩之和等于输入值

标签:

原文地址:http://www.cnblogs.com/cheneva/p/5769573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!