Find duplicate element in array in time O(n)

前端 未结 24 2587
余生分开走
余生分开走 2020-11-27 10:07

I have been asked this question in a job interview and I have been wondering about the right answer.

You have an array of numbers from 0 to n-1, one o

相关标签:
24条回答
  • 2020-11-27 10:50

    We can do using hashMap efficiently:

    Integer[] a = {1,2,3,4,0,1,5,2,1,1,1,};
    HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int x : a)
    {
        if (map.containsKey(x))  map.put(x,map.get(x)+1);
        else map.put(x,1);
    }
    
    Integer [] keys = map.keySet().toArray(new Integer[map.size()]);
    for(int x : keys)
    {
        if(map.get(x)!=1)
        {
            System.out.println(x+" repeats : "+map.get(x));
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:52

    This video If Programming Was An Anime is too fun not to share. It is the same problem and the video has the answers:

    1. Sorting
    2. Creating a hashmap/dictionary.
    3. Creating an array. (Though this is partially skipped over.)
    4. Using the Tortoise and Hare Algorithm.

    Note: This problem is more of a trivia problem than it is real world. Any solution beyond a hashmap is premature optimization, except in rare limited ram situations, like embedded programming.

    Furthermore, when is the last time you've seen in the real world an array where all of the variables within the array fit within the size of the array? Eg, if the data in the array is bytes (0-255) when do you have an array 256 elements or larger without nulls or inf within it, and you need to find a duplicate number? This scenario is so rare you will probably never get to use this trick in your entire career.

    Because it is a trivia problem and is not real world the question, I'd be cautious accepting an offer from a company that asks trivia questions like this, because people will pass the interview by sheer luck instead of skill. This implies the devs there are not guaranteed to be skilled, which unless you're okay teaching your seniors skills, you might have a bad time.

    0 讨论(0)
  • 2020-11-27 10:54

    We have the original array int A[N]; Create a second array bool B[N] too, of type bool=false. Iterate the first array and set B[A[i]]=true if was false, else bing!

    0 讨论(0)
  • 2020-11-27 10:54

    Here is the simple solution with hashmap in O(n) time.

    #include<iostream>
    #include<map>
    using namespace std;
    
    int main()
    {
        int a[]={1,3,2,7,5,1,8,3,6,10};
        map<int,int> mp;
        for(int i=0;i<10;i++){
    
            if(mp.find(a[i]) == mp.end())
                mp.insert({a[i],1});
            else
                mp[a[i]]++;
        }
    
        for(auto i=mp.begin();i!=mp.end();++i){
            if(i->second > 1)
                cout<<i->first<<" ";
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 10:55

    This can be done in O(n) time and O(1) space.

    (The algorithm only works because the numbers are consecutive integers in a known range):

    In a single pass through the vector, compute the sum of all the numbers, and the sum of the squares of all the numbers.

    Subtract the sum of all the numbers from N(N-1)/2. Call this A.

    Subtract the sum of the squares from N(N-1)(2N-1)/6. Divide this by A. Call the result B.

    The number which was removed is (B + A)/2 and the number it was replaced with is (B - A)/2.

    Example:

    The vector is [0, 1, 1, 2, 3, 5]:

    • N = 6

    • Sum of the vector is 0 + 1 + 1 + 2 + 3 + 5 = 12. N(N-1)/2 is 15. A = 3.

    • Sum of the squares is 0 + 1 + 1 + 4 + 9 + 25 = 40. N(N-1)(2N-1)/6 is 55. B = (55 - 40)/A = 5.

    • The number which was removed is (5 + 3) / 2 = 4.

    • The number it was replaced by is (5 - 3) / 2 = 1.

    Why it works:

    • The sum of the original vector [0, ..., N-1] is N(N-1)/2. Suppose the value a was removed and replaced by b. Now the sum of the modified vector will be N(N-1)/2 + b - a. If we subtract the sum of the modified vector from N(N-1)/2 we get a - b. So A = a - b.

    • Similarly, the sum of the squares of the original vector is N(N-1)(2N-1)/6. The sum of the squares of the modified vector is N(N-1)(2N-1)/6 + b2 - a2. Subtracting the sum of the squares of the modified vector from the original sum gives a2 - b2, which is the same as (a+b)(a-b). So if we divide it by a - b (i.e., A), we get B = a + b.

    • Now B + A = a + b + a - b = 2a and B - A = a + b - (a - b) = 2b.

    0 讨论(0)
  • 2020-11-27 10:57

    This program is based on c# and if you want to do this program using another programming language you have to firstly change an array in accending order and compare the first element to the second element.If it is equal then repeated number found.Program is

    int[] array=new int[]{1,2,3,4,5,6,7,8,9,4};
    Array.Sort(array);
    for(int a=0;a<array.Length-1;a++)
    {
      if(array[a]==array[a+1]
      {
         Console.WriteLine("This {0} element is repeated",array[a]);
       }
    }
    Console.WriteLine("Not repeated number in array");
    
    0 讨论(0)
提交回复
热议问题