leetcode 面试题57 - II. 和为s的连续正数序列【双指针】

方法1:

暴力法,从1~target/2遍历,判断被遍历数字之后的连续n个数字之和是否等于target,若等于,则在List中加入该数字序列组成的数组,若sum>target后,跳出本次循环,开始从下一个数字开始遍历。

class Solution {
    public int[][] findContinuousSequence(int target) {
        List<int[]> ans = new ArrayList<>();
        for(int i=1; i<=target/2; i++){
            int temp = target;
            int k = i;
            while(temp>0){
                temp = temp - k;
                k++;
                if(temp == 0){
                    int[] a = new int[k-i];
                    int b = i;
                    for(int j=0; j<a.length; j++){
                        a[j] = b;
                        b++;
                    }
                    ans.add(a);
                }
            }            
        }    
        return ans.toArray(new int[ans.size()][0]);
    }
}

方法2:

为了避免重复的遍历,可以考虑使用双指针构建滑动窗口,起始窗口为1,2,当窗口内元素之和sum小于target时,右指针右移,sum=sum+right,sum大于target时,sum=sum-left,左指针右移,当sum==target时,将left和right之间的数放入数组并添加到list中,当右指针越过target/2时,结束运算。

class Solution {
    public int[][] findContinuousSequence(int target) {
        int left = 1;
        int right = 2;
        List<int[]> res = new ArrayList<>();
        int sum = left + right;
        while(right<=target/2+1){
            if(sum < target){
                right++;
                sum+=right;
            }else if(sum > target){
                sum-=left;
                left++;
            }else{
                int[] arr = new int[right-left+1];
                int temp = left;
                for(int i=0; i<arr.length; i++){
                    arr[i] = temp;
                    temp++;
                }
                res.add(arr);
                sum-=left;
                left++;
            }
        }
        return res.toArray(new int[0][]);
    }
}
发布了55 篇原创文章 · 获赞 0 · 访问量 791

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/104692088
今日推荐