劍指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()][]);
    }
}

效率:

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