topic link
Niuke.com online oj question - the continuous positive number sequence whose sum is S
topic description
Xiao Ming likes mathematics very much. One day when he was doing a mathematics homework, he asked to calculate the sum of 9~16, and he immediately wrote down that the correct answer was 100. But he is not satisfied with this, he is wondering how many continuous positive number sequences have a sum of 100 (including at least two numbers). Before long, he got another set of consecutive positive numbers with a sum of 100: 18, 19, 20, 21, 22. Now I leave the question to you, can you quickly find out all the consecutive positive numbers whose sum is S?
Data range: 0<n≤100
Advanced: Time complexity O(n)
Return value description:
Output all continuous positive sequence whose sum is S. The sequence is in ascending order within the sequence, and the sequence is in ascending order of the starting number between sequences
Topic example
Example 1
Enter:
9
Return value:
[[2,3,4],[4,5]]
Example 2
Input:
0
return value:
[]
problem solving ideas
We need to determine the starting position and ending position of the continuous positive number sequence. We can define the starting position as start and the ending position as end. This sequence is a closed interval
Calculates the sum total of all elements in start and end
- If total is less than S, it means that the value in the sequence is too small, just end++
- If total is less than S, it means that the value in the sequence is too large, just start++
- If total is equal to S, just add all the elements in start and end to the result
For example:
target S = 9
, total = 3, less than S, end++,
total = 6, less than S, end++,
total = 10, greater than S, start++,
total = 9 == S, set 2, 3, 4 This sequence is added to the result set, start++, end++
Continue the above operation
At this time total = 9 == S, add the sequence of 4, 5 into the result set, start++, end++
total = 10 at this time, greater than S, start++
at this time start == end, so the right side is no longer possible The sum is a continuous positive number sequence of S, and the loop is terminated
full code
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
int start = 1;
int end = 2;
while(start < end){
int total = (start + end) * (end - start + 1) / 2;
if(sum == total){
ArrayList<Integer> tmp = new ArrayList<>();
for(int i = start; i <= end; i++){
tmp.add(i);
}
result.add(tmp);
start++;
end++;
} else if(total < sum){
end++;
} else {
start++;
}
}
return result;
}
}