如何在 Java 中查詢和給定數字相等的連續子陣列?


查詢和給定數字相等的連續子陣列:

  • 遍歷該陣列。
  • 逐個新增每個元素後面的 n 個元素,當總和等於所需值時,列印子陣列。

示例

import java.util.Arrays;
import java.util.Scanner;
public class sub_arrays {
   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 required sum: ");
      int reqSum = sc.nextInt();
      System.out.println("The array created is: "+Arrays.toString(myArray));
      System.out.println("sub arrays whose sum is: "+reqSum);
      for(int i=0; i<myArray.length; i++){
         int sum = 0;
         for (int j=i; j<myArray.length; j++){
            sum = sum + myArray[j];
            if(sum == reqSum){
               System.out.println(Arrays.toString(Arrays.copyOfRange(myArray, i, j+1)));
            }
         }
      }
   }
}

輸出

Enter the size of the array that is to be created:
10
Enter the elements of the array:
5
4
1
2
3
4
1
4
5
5
Enter the required sum:
10
The array created is: [5, 4, 1, 2, 3, 4, 1, 4, 5, 5]
sub arrays whose sum is: 10
[5, 4, 1]
[4, 1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 1]
[1, 4, 5]
[5, 5]

更新時間: 02-Aug-2019

2,000+ 次瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.