JZ42 和为S的两个数字

和为S的两个数字

https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&&tqId=11195&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

2021年9月8日10:59:46
2021年9月8日11:09:56

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        ArrayList<Integer> res = new ArrayList<Integer>();

        if(array.length < 2) return res;

        int left = 0;
        int right = array.length-1;

        while(left<right){
            if(array[left] + array[right] == sum) {
                res.add(array[left]);
                res.add(array[right]);
                return res;
            }
            else if(array[left] + array[right] > sum) right --;
            else left ++;
        }

        return res;


    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务