题目描述:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24输入一个正整数 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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24class 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()][]); } }
效率:
最后
以上就是威武机器猫最近收集整理的关于剑指offer-面试题57 - II. 和为s的连续正数序列的全部内容,更多相关剑指offer-面试题57内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复