簡體   English   中英

您能幫我找出此代碼中的錯誤嗎? 我似乎不明白為什么它不起作用?

[英]Can you help me identify the error in this code? I dont seem to understand why it isn't working?

https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays

我遇到問題的鏈接...

我的邏輯是從數組的末尾開始循環並向前移動,檢查哪些元素在適當的位置,然后交換以使這些元素在正確的位置,我在下面附加我的代碼。 我一一交換,因為這就是他們在示例測試用例中展示的方式。

    static void minimumBribes(int[] q) {

    int moves = 0;
    boolean tc = false;

    for(int i = q.length-1; i >= 0; i--){

        if(q[i] != i+1 && q[i] >= (i+1)){

            int diff = q[i] - (i+1);
            if(diff > 2){

                System.out.println("Too chaotic");
                tc = true;
            }else{

                moves = moves + diff;
                for(int j = 1; j <= diff; j++){

                    arrSwap(q, i-1+j, i+j);
                }
                i--;
            }
        }else{

            continue;
        }
    }
    if(tc == false){

        System.out.println(moves);
    }

}

public static void arrSwap (int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;

}

輸入:1 2 5 3 4 7 8 6

輸出3

預期產量:4

您可以使用Bobble排序解決此問題。這是我的代碼:

static void minimumBribes(int[] q) {
    int []res=new int[q.length];
    boolean change=true;
    for(int i=0;i<q.length;i++)
        res[i]=0;
    while(change){
        change=false;
        for(int i=0,j=i+1;j<q.length;i++,j++){
            if(q[i]>q[j]){
                res[q[i]-1]++;
                arrSwap(q,i,j);
                change=true;
            }
        }
    }
    int n=0;
    for(int i=0;i<q.length;i++){
        if(res[i]>2){
            System.out.println("Too chaotic");
            return;
        }
        else
            n+=res[i];
    }
    System.out.println(n);
}

public static void arrSwap (int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

我的代碼可能不是最佳解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM