简体   繁体   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 https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays

The link to the question I'm having trouble in... 我遇到问题的链接...

My logic was to start a loop from the end of the array and move forwards, checking which elements are in position, and swapping to get the elements in their right position, I'm attaching my code below. 我的逻辑是从数组的末尾开始循环并向前移动,检查哪些元素在适当的位置,然后交换以使这些元素在正确的位置,我在下面附加我的代码。 I swap one by one because that's how they showed it in the sample test case. 我一一交换,因为这就是他们在示例测试用例中展示的方式。

    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;

}

Input: 1 2 5 3 4 7 8 6 输入:1 2 5 3 4 7 8 6

Output: 3 输出3

Expected Output: 4 预期产量:4

You can use Bobble sortting solve this problem.Here is my code: 您可以使用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;
}

My code may be not the best solution. 我的代码可能不是最佳解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM