如何在 Java 陣列中查詢所有元素對,其和等於給定數字?


如要在 Java 陣列中查詢所有元素對,其和等於給定數字 −

  • 將陣列中的每個元素與剩餘所有元素相加(自身除外)。
  • 驗證和是否等於所需數字。
  • 如果為真,列印其索引。

示例

import java.util.Arrays;
import java.util.Scanner;
public class sample {
   public static void main(String args[]){
      //Reading the array from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      //Reading the number
      System.out.println("Enter the number: ");
      int num = sc.nextInt();
      System.out.println("The array created is: "+Arrays.toString(myArray));
      System.out.println("indices of the elements whose sum is: "+num);
      for(int i=0; i<myArray.length; i++){
         for (int j=i; j<myArray.length; j++){
            if((myArray[i]+myArray[j])== num && i!=j){
               System.out.println(i+", "+j);
            }
         }
      }
   }
}

輸出

Enter the size of the array that is to be created:
8
Enter the elements of the array:
15
12
4
16
9
8
24
0
Enter the number:
24
The array created is: [15, 12, 4, 16, 9, 8, 24, 0]
indices of the elements whose sum is: 24
0, 4
3, 5
6, 7

更新於:02-Aug-2019

6K+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始使用
廣告
© . All rights reserved.