美文网首页
递增数组中和为s的两个数字

递增数组中和为s的两个数字

作者: shuixingge | 来源:发表于2016-05-01 17:08 被阅读18次

思路:
创建两个指针,初始位置分别指向数组的头部和尾部,把对应位置的数字求和,比较和s的大小,如果相等,即为所求,如果大于s,则把尾指针向前移动,如果小于s,则把头指针向前移,知道找到和为s的两个数字的数字为止。

public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        ArrayList<Integer> list=new ArrayList<>();
        if(array==null||array.length<2)
             return list;
        int head=0;
        int tail=array.length-1;
        while(head<tail){
            int s=array[head]+array[tail];
            if(sum==s){
                 list.add(array[head]);
                 list.add(array[tail]);
                break;
            }else if(s>sum){
                tail--;
            }else
                head++;
        }
            
         return list;
        
    }
}

相关文章

网友评论

      本文标题:递增数组中和为s的两个数字

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