双端队列
1. 求解连续数列
# 用例
7611 86
import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] split = in.nextLine().split(" ");
int sum = Integer.parseInt(split[0]);
int count = Integer.parseInt(split[1]);
Deque<Integer> deque = new ArrayDeque<>();
int temp = 0;
for (int i = 1; i <= count;i++) { // 【1,86】
deque.add(i);
temp += i;
}
if (temp == sum){ // 判断前 k 个是否已经是答案
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= count; i++) {
sb.append(i + " ");
}
System.out.println(sb.toString().trim());
return;
}
for (int i = count + 1; i < 100000; i++) { // 这里从 87 开始了,所以 count + 1
Integer first = deque.removeFirst();
deque.add(i);
temp = temp - first + i;
if (temp > sum){
System.out.println(-1);
return;
}
if (temp == sum){
StringBuilder sb = new StringBuilder();
for (int j = i - count + 1; j <= i; j++) {
sb.append(j + " ");
}
System.out.println(sb.toString().trim());
return;
}
}
System.out.println(-1);
}
}