返回3个数组中每个从最小到最大的差异相同的整数

时间:2017-04-06 14:24:37

标签: java arrays

所以,我想插入一个数字数组,并按从最大到最小的顺序返回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
}

1 个答案:

答案 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);

}