美文网首页
《剑指offer第二版》面试题57:和为s的两个数字(java)

《剑指offer第二版》面试题57:和为s的两个数字(java)

作者: castlet | 来源:发表于2020-02-28 20:25 被阅读0次

    题目描述

    • 输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得他们的和正好是s。如果有多对数字的和是s,输出任意一对即可。

    解题思路

    1. 分别用两个指针begin和end指向数组A的开头和尾部。
    2. 如果A[begin] 和A[end] 的和大于s,由于数组是排好序的,则end 减一。
    3. 如果和小于s,则begin加1。
    4. 如果和等于s,则找到数字返回。

    代码

    int[] findNumberWithSum(int[] arrs, int sum) {
        if (arrs == null || arrs.length <= 1) {
            return null;
        }
        int beginIndex = 0;
        int endIndex = arrs.length - 1;
    
        while (beginIndex < endIndex) {
            if (arrs[beginIndex] + arrs[endIndex] > sum) {
                endIndex--;
            } else if (arrs[beginIndex] + arrs[endIndex] < sum) {
                beginIndex ++;
            } else {
                return new int[] {arrs[beginIndex], arrs[endIndex]};
            }
        }
        return null;
    }
    

    相关文章

      网友评论

          本文标题:《剑指offer第二版》面试题57:和为s的两个数字(java)

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