剑指offer T57-|| 和为s的连续正整数序列(滑动窗口)

    技术2022-07-20  68

    思想:借鉴上一题的思路,这里也采用双指针,但有所改动,这里采用滑动窗口的思想: 声明两个指针:left ,right,初始均指向1,[left,right]即为一个连续子序列,也就是窗口 然后通过不断右移right然后根据结果去调整left来使[left,right]区间内的值成为我们想要找的target 让left,right指针只做右移操作是为了保证时间复杂度为O(n),而如果运行这些指针左移的话时间复制度就不一定是O(n)了,此时更像回溯

    class Solution { public int[][] findContinuousSequence(int target) { if(target<=1) return new int[0][]; List<int[]> res = new ArrayList<>(); int left = 1,right = 1,sum = 0; while(right<target){ sum+=right; while(sum>target){//这里必须要用while而不是if,因为后面的数肯定更大,所以你只能令sum不断减小直到其<=target为止 sum-=left; left++; } if(sum==target){ int[]temp = new int[right-left+1]; int idx = 0; for(int i=left;i<=right;i++){ temp[idx++] = i; } res.add(temp); } right++; } return res.toArray(new int[0][]); } }
    Processed: 0.009, SQL: 9