3月打卡活动第6天 面试题第57题:和为s的连续正数序列(简单)
- 题目:输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
- 解题思路:双指针方法,和大于t,左指针就向右移,小于t,右指针向右移。
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> ansList = new ArrayList<>();
int start = 1;
int end = 0;
int sum = 0;
while(end<=(target+1)/2){
if(sum < target){
end++;
sum += end;
}else if(sum > target){
sum-=start;
start++;
}else if(sum == target){
int j = 0;
int[] ans = new int[end-start+1];
for(int i=start;i<=end;i++){
ans[j++]= i;
}
ansList.add(ans);
end++;
sum += end;
}
}
return ansList.toArray(new int[0][]);
}
}
- 题解做法:这个做法变成了数学找规律题,如果(t-i)/(i++)=0,就有i个元素在数组里,我也不知道这规律是咋来的。。。不过双100%也是太棒了!
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> result = new ArrayList<>();
int i = 1;
while(target>0)
{
target -= i++;
if(target>0 && target%i == 0)
{
int[] array = new int[i];
for(int k = target/i, j = 0; k < target/i+i; k++,j++)
{
array[j] = k;
}
result.add(array);
}
}
Collections.reverse(result);
return result.toArray(new int[0][]);
}
}
作者:VaporMax
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/java-shuang-100-by-vapormax/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。