剑指 Offer 57

List<List<Integer>> res = new ArrayList<>();
    public int[][] findContinuousSequence(int target) {

        List<Integer> list = new ArrayList<>();
        findOne(target);
        int l = res.size();
        if(l == 0) return new int[0][0];
        int[][] res = new int[l][];
        for(int i = 0;i<l;i++){
            List<Integer> y = this.res.get(i);
            int len = y.size();
            int[] r = new int[len];
            for(int j = 0;j<len;j++){
                r[j] = y.get(j);
            }
            res[i] = r;
        }
        return res;
    }

    private void findOne(int target) {
        int j = 1;
        while(j<=target/2) {
            int i = j;
            int m = target;
            List<Integer> list = new ArrayList<>();
            while (i <= target / 2 + 1) {
                if (i < m) {
                    list.add(i);
                    m = m - i;
                    i++;
                } else if (i == m) {
                    list.add(i);
                    res.add(list);
                    j++;
                    break;
                }else{
                    j++;
                    break;
                }
            }
        }
    }
List<int[]> res = new ArrayList<>();
public int[][] findContinuousSequence(int target) { //方法2-------------------------------------------------------------
//双指针
if(target<3) return new int[0][0];
int small = 1;
int big = 2;
int mid = (1+target)/2;
int curSum = small + big;
while (small<target) {
if(curSum == target){
//将从small到big的连续数字组成的数组添加进去;
addList(small,big);
}
while (curSum>target && small<mid){
curSum -= small;
small ++;

if(curSum == target){
//将从small到big的连续数字组成的数组添加进去;
addList(small,big);
}
}
big ++;
curSum += big;
}
int[][] x = new int[res.size()][];
for(int i = 0;i<res.size();i++){
x[i] = res.get(i);
}
return x;
}

private void addList(int small,int big){
int[] nums = new int[big-small+1];
int i = 0;
while(i<big-small+1){
nums[i] = small;
small++;
i++;
}
res.add(nums);
}

 

 双指针

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/13542187.html