第14题:查找升序数组中的两数,使其和为输入数字


欢迎转载,转载请注明出处:http://blog.csdn.net/alading2009/article/details/45080773


第14题:输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。要求: 时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。



两头向中间靠拢,因为是升序数组,两数之和大了就尾指针前移,两数之和小了就头指针后移。


代码

package test014;

/**
 * Created by cq on 2015/4/16.
 * 第14题:输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。
 * 要求:  时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。
 * 例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。
 */
public class Test014 {
    public static String getPair(int[] arr, int k){
        if (arr == null || arr[0] >= k){
            return null;
        }

        int head = 0, tail = arr.length-1;

        //如果尾上的值比k大,则尾指针前移,直到到达一个比k小的值
        while (head < tail && arr[tail] >= k){
            tail--;
        }

        //从数组的两头向中间扫描,最差情况下整个数组被扫描一遍
        while (head < tail){
            if (arr[head] + arr[tail] == k){
                return arr[head]+" "+arr[tail];
            }
            else if (arr[head] + arr[tail] > k){
                tail--;
                continue;
            }
            else
                head++;
        }

        return null;
    }
    public static void main(String[] args){
        int[] arr = {1,2,4,7,11,15};
        System.out.println("数组中和为15的两数为:"+getPair(arr,15));
        System.out.println("数组中和为19的两数为:"+getPair(arr,19));
        System.out.println("数组中和为21的两数为:"+getPair(arr,21));
    }
}


执行结果

Connected to the target VM, address: '127.0.0.1:28571', transport: 'socket'
数组中和为15的两数为:4 11
数组中和为19的两数为:4 15
数组中和为21的两数为:null
Disconnected from the target VM, address: '127.0.0.1:28571', transport: 'socket'

Process finished with exit code 0
版权所有,转载请注明出处 http://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/
原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041983.html