Java Solution Accepted in Java7


#1

Try switching to Java-7. My code got TLE in java-8, but got accepted in java-7

Here’s the code for reference (O(n) complexity):

public int[] solve(int[] A, int B) {
        int len = A.length;
        //int counter=len;
        int position[] = new int[len+1];

        for (int i=0; i<len; i++){
            position[A[i]] = i;
        }

        //System.out.println(Arrays.toString(position));

        //System.out.println("counter: "+counter);

        for (int i=0; i<len && B>0; i++){
            if (A[i]!=len-i){
                A[position[len-i]] = A[i];

                int temp = position[A[i]];
                position[A[i]] = position[len-i];
                //position[len-i] = i;

                A[i] = len-i;
                B--;
            }
            /*System.out.println(Arrays.toString(A));
            System.out.println("positions updated: "+Arrays.toString(position));
            System.out.println();*/
        }

        return A;
    }