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

题目描述:

输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

 

示例 1:

输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:

输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
 

限制:

1 <= target <= 10^5
 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答:

class Solution {
    public int[][] findContinuousSequence(int target) {
        int lo=1,hi=1,sum=1;
        List<int []> res = new ArrayList<>();
        while(lo<=target/2){
            if(sum<target){
                hi++;
                sum+=hi;
            }else if(sum>target){
                sum-=lo;
                lo++;
            }else{
                int[] arr =new int[hi-lo+1];
                for(int i=lo;i<=hi;i++){
                    arr[i-lo] = i;  
                }
                res.add(arr);
                sum -=lo;
                lo++;
            }
        }
        return res.toArray(new int [res.size()][]);
    }
}

效率:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章