【问题标题】:Find the minimum number of swaps required such that all the 0s and all the 1s are together找出所有 0 和所有 1 在一起所需的最小交换次数
【发布时间】:2019-07-30 06:12:15
【问题描述】:

我需要找到所需的最小交换次数,以使所有 0 和所有 1 都在一起。

这是我的代码:

class GFG {

    static int minSwaps(int arr[], int n) {
        int noOfOnes = 0;
        for (int i = 1; i <= n; i++) {
            if (arr[i] == 1)
            noOfOnes++;
        }
        int x = noOfOnes;
        int maxOnes = Integer.MIN_VALUE;
        int preCompute[] = new int[n];
        if (arr[0] == 1)
            preCompute[0] = 1;
        for (int i = 2; i < n; i++) {
            if (arr[i] == 1) {
                preCompute[i] = preCompute[i - 1] + 1;
            } else {
                preCompute[i] = preCompute[i - 1];
            }
        } 

        for (int i = x - 1; i < n; i++) {
            if (i == (x - 1)) {
                noOfOnes = preCompute[i];
            } else {
                noOfOnes = preCompute[i] - preCompute[i - x];
            }
            if (maxOnes < noOfOnes)
                maxOnes = noOfOnes;
        }

        int noOfZeroes = x - maxOnes;
        return noOfZeroes;
    }

    public static void main (String[] args) { 
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        for (int test = 1; test <= t; test++) {
            int n = s.nextInt();
            int[] a = new int[n];
            for (int j = 1; j <= n; j++) {
                a[j] = s.nextInt();
            }
            System.out.println(minSwaps(a, n));
            System.out.println("\n");
        }
    }
}

我收到了ArrayIndexOutOfBoundsException

error : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at GFG.main(solution.java:56)

【问题讨论】:

  • 你的问题是什么?
  • main 方法中的这个循环有错误的界限:for (int j = 1; j &lt;= n; j++)。由于之前声明的int a = new int[n];,它将导致Exception。找出正确的界限(提示:长度不等于索引)。我可以直接告诉你正确的,但那将意味着窃取你的学习效果!
  • 错误:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 4 at GFG.main(solution.java:56) 为什么我会收到此错误

标签: java arrays indexoutofboundsexception


【解决方案1】:

看起来您正在尝试进行冒泡排序。 所以我复制了这个bubblesort pseudocode implementation off of Wikipedia 并用计数器增加了它:

bubbleSort(Array A)
  swap_counter = 0          // start at 0
  for (n=A.size; n>1; --n){
    for (i=0; i<n-1; ++i){
      if (A[i] > A[i+1]){
        A.swap(i, i+1)
        swap_counter++      // count a swap
      }
    }
  }
  return swap_counter       // return the result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 2021-12-08
    • 2011-04-17
    • 2022-01-21
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多