剑指offer:和为s的连续正数序列

转自leetcode剑指offer
leetcode官方挺多解法的,比较直观的是暴力解法,一开始不知道list里面能装数组int[]这样,浪费了很多时间在转换上面,下面是看了题解之后写的代码:

class Solution {
    public int[][] findContinuousSequence(int target) {
        if(target<3) return new int[0][0];
        int n=1;
        List<int[]> resList=new LinkedList<>();
        while(n<=target/2){
            int tot=0;
            for(int i=n;i<target;i++){
                tot+=i;
                if(tot>target)break;
                if(tot==target){
                    int[] tempArr=new int[i-n+1];
                    for(int j=n;j<=i;j++){
                        tempArr[j-n]=j;
                    }
                    resList.add(tempArr);
                    break;
                }
            }
            n++;
        }
        int[][] res=new int[resList.size()][];
        for(int i=0;i<resList.size();i++){
            res[i]=resList.get(i);
        }
        return res;
    }
}

官方的比较简洁,也贴上:

class Solution {
    public int[][] findContinuousSequence(int target) {
        List<int[]> vec = new ArrayList<int[]>();
        int sum = 0, limit = (target - 1) / 2; // (target - 1) / 2 等效于 target / 2 下取整
        for (int i = 1; i <= limit; ++i) {
            for (int j = i;; ++j) {
                sum += j;
                if (sum > target) {
                    sum = 0;
                    break;
                } else if (sum == target) {
                    int[] res = new int[j - i + 1];
                    for (int k = i; k <= j; ++k) {
                        res[k - i] = k;
                    }
                    vec.add(res);
                    sum = 0;
                    break;
                }
            }
        }
        return vec.toArray(new int[vec.size()][]);
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/mian-shi-ti-57-ii-he-wei-sde-lian-xu-zheng-shu-x-2/
来源:力扣(LeetCode
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值