美文网首页程序员
算法--在给定的有序数组中寻找两个之和为n的两个元素

算法--在给定的有序数组中寻找两个之和为n的两个元素

作者: reedthinking | 来源:发表于2017-06-14 17:49 被阅读0次

因为数组有序,所以原理是用两个指针,一个指向起始,一个指向末尾,然后判断当前两个元素之和与目标sum的大小关系。

public class FindTwoSum {

    public void findTwoSum(int[] a, int n, int sum) {
        int left = 0;
        int right = n - 1;
        int curSum = 0;

        //当left >= right,两个指标相遇,说明a数组中不存在和为sum的两个数
        while (left < right) {
            //计算当前和
            curSum = a[left] + a[right];
            //过大,减小一些
            if (curSum > sum) {
                right--;
            } else if (curSum < sum) { //太小,大一些
                left++;
            } else { //刚好,返回
                System.out.print(a[left]);
                System.out.print(" ");
                System.out.print(a[right]);
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] a = { 1, 3, 5, 7, 9, 11 };
        FindTwoSum fts = new FindTwoSum();
        fts.findTwoSum(a, 6, 8);
    }
}

相关文章

网友评论

    本文标题:算法--在给定的有序数组中寻找两个之和为n的两个元素

    本文链接:https://www.haomeiwen.com/subject/nvkeqxtx.html