Leetcode面试题57 - II. 和为s的连续正数序列

在这里插入图片描述
思路:我只想到了暴力的方法,但是其实双指针才是正解

class Solution {
    public int[][] findContinuousSequence(int target) {
        //双指针法
        int p1 = 1,p2 = 2;
        ArrayList<int[]> list = new ArrayList<>();
        while(p1 < p2){
            int sum = (p1+p2)*(p2-p1+1)/2;
            if(sum < target){
                p2++;
            }else if(sum > target){
                p1++;
            }else{
                int[] tmp = new int[p2-p1+1];
                for(int i = p1;i <= p2;i++) tmp[i-p1] = i;
                p1++;
                list.add(tmp);
            }
        }
        return list.toArray(new int[0][]);
    }
}

注意:
列表转数组的表达
list.toArray(new int[0][]);

发布了169 篇原创文章 · 获赞 5 · 访问量 7677

猜你喜欢

转载自blog.csdn.net/fsdgfsf/article/details/104700846