【样例说明】
包含 2、6、4、10、20 的最短的等差数列是 2、4、6、8、10、12、14、16、 18、20。
思路:
1、先判断进行排序,然后判断最小的数字和第二小的数字的差,那个差就是常数,也就是公差d。
2、然后我们按照这个依次排列,也就是+d,然后输出这个我们添加好的数列。
代码实现:
//等差数列
public class Main {
public static void main(String[] args) {
long time = System.nanoTime();
String str = "2 6 4 10 20";
String[] split = str.split(" ");//空格进行分割
//字符串数组转换Integer类型数组
Integer[] arr = new Integer[split.length];
for (int i = 0; i < split.length; i++) {
arr[i] = Integer.parseInt(split[i]);
}
//原等差数列,数组转为List,比较好扩容
List<Integer> arrList = Arrays.asList(arr);
// 排序原序列
Collections.sort(arrList);
System.out.println(arrList);
// 最小公差 = 第二小项 - 最小项
int d = arrList.get(1) - arrList.get(0);
System.out.println("公差:" + d);
//存储新等差数列的List
List<Integer> arrList2 = new ArrayList<>();
//补充等差数列
int i = 1;
arrList2.add(arrList.get(0));
while (true) {
arrList2.add(arrList2.get(i - 1) + d); //添加到末尾
//退出条件
if (arrList2.get(i) == arr[arr.length - 1]) {
break;
}
i++;
}
// 排序新序列
Collections.sort(arrList2);
// 计算新序列是否包含原序列
int cous = 0;
for (int j = 0; j < arr.length; j++) {
if (arrList2.contains(arr[j])) {
cous++;
}
//计数 = 原序列长度,说明包含,那就输出新数列长度,并结束
if (cous == arr.length) {
System.out.println(arrList2.size());
break;
}
}
long time2 = System.nanoTime();
System.out.println(time2 - time);
}
}
拓展:
等差数列:
等差数列是指从第二项起,每一项与它的前一项的差等于同一个常数的一种数列,常用A、P表示。这个常数叫做等差数列的公差,公差常用字母d表示。