所以,我想插入一个数字数组,并按从最大到最小的顺序返回3个数字,每个数字之间的差异相同。
2 3 7 9 12.
2 7 12 because 2+5=7, 7+5=12.
以下代码是我的尝试。我制作了3个 for
循环 。
所以:(first number - second number) = (second number - third number)
public static void main(String[] args) {
int n;
int num1;
int num2;
int num3;
int dif;
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers do you want to choose from? ");
n = scan.nextInt();
int nums[] = new int[n];
System.out.println("Please input the integers: ");
for (int i=0; i<n ;i++){
nums[i] = scan.nextInt();
}
System.out.println(" ");
for (int i=0; i<n; i++){
for (int j=i+1; j<n; j++){ //compare element i to the rest of the array
if(nums[j]<= nums[i]){ //if a num at j is smaller than num at i,
num3 = nums[i]; //then num3 is num at i
num2 = nums[j]; //and num2 is num at j
dif = num3 - num2; //find the difference
for(int k=i+j+1; k<n; k++){
if(num2 == (nums[k]+ dif)){ //if num2 is num at k + difference
num1 = nums[k]; //then num1 must be num at k
}
}
}
}
}
System.out.print(num3); //This is the effort printing them out
System.out.print(num2); //But for some reason I couldn't
System.out.print(num1); //even I initialized num3,2,1 outside of the for loop
scan.close(); //closing the scanner object
}
答案 0 :(得分:0)
如果您正在寻找更快的一个,这适用于两个fors。
public static void main(String[] args) throws Exception {
List<Integer> integers = Arrays.asList(1, 3, 5, 9, 17);
Map<String, Integer> differenceMap = new HashMap<>();
for (int i = 0; i < integers.size(); i++) {
int first = integers.get(i);
for (int j = i + 1; j < integers.size(); j++) {
int second = integers.get(j);
int difference = second - first;
int next = difference + second;
if (integers.contains(next)) {
differenceMap.put(first + " - " + second + " - " + next, difference);
}
}
}
differenceMap.keySet().forEach(System.out::println);
}