简体   繁体   中英

Removing odd occurence value from an array

https://app.codility.com/demo/results/trainingCP6965-NRG/

import java.util.*;

    class Solution {
          public int solution(int[] A) {

            ArrayList<Integer> B = new ArrayList<Integer>();

            for(int i = 0 ; i < A.length ; i++){
                B.add(A[i]);
            }

            while(B.size() != 1){

                for(int j = 1; j <B.size();j++){

                    if(B.get(0) == B.get(j)){
                        B.remove(j);
                        B.remove(0);
                        break;
                    }

                    if(j == B.size()-1 && B.get(0) != B.get(j)){
                        return B.get(0);
                    }
                }
            }

            return B.get(0);
        }
    }

I can pass until the Correctness tests where n=601. but i can't pass on the Performance tests because of wrong answer.
So i want to know why my code is wrong.
https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/

Your code's running time is O(n^2) due to the nested loops, so it's too slow for large inputs.

On each iteration of your outer loop you detect and eliminate a single pair of equal elements. This means there would be (n-1)/2 iterations of that loop.

Your inner loop may iterate over all the remaining elements of the array in each iteration, so at the worst case, the first execution of the inner loop will have n iterations, the second will have n-2 iterations, and so on.

Therefore, the total running time is bound by

n + n - 2 + n - 4 + ... + 3 = (n + 3)*(n - 1)/4 = O(n^2)

I suggest you use a HashSet<Integer> to store the elements you encounter if not present, and remove them if they are present. This will take linear time ( O(n) ).

class Solution {
    public int solution(int[] A) {
        Set<Integer> set = new HashSet<Integer>();
        for(int i = 0; i < A.length; i++){
            if (!set.add(A[i])) { // add will return false if A[i] is already in the Set,
                                 // in which case we know we found a pair of equal numbers,
                                 // so we remove that number
                set.remove(A[i]);
            }
        }
        return set.iterator().next(); // according to the problem description, there should 
                                      // be exactly one element left
    }
}

A faster solution is to use Bitwise XOR(^) :

class Solution {
    public int solution(int[] A) {
        int result = 0;
        for(int i = 0; i < A.length; i++){
            result = result ^ A[i];
        }
        return result;  
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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