Distinguishing extra element from two arrays?

后端 未结 19 642
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 09:45

One of my friend was asked this question in an interview -

  • You have given two integer arrays each of size 10.
  • Both contains 9 equal elements (say 1 t
19条回答
  •  情话喂你
    2020-12-28 10:43

    Technically, you can do it in constant time, since the arrays (and values within them) are limited. For the generalized problem, we have to make out something trickier.

    Here's a linear-time solution.

    First, we should build a hash based on one array. Value lookup in a hash table takes O(1 + k/n) comparisons [1], where k is the length of hash table. Thus iteration over the first array (that contains n elements) and lookups for each value takes O(n+k).

    Then we iterate the other one, looking up for each element in the hash. When an element is not found -- that's unique one from the other array. (O(n+k) again). Then we iterate hash to look for the second unique element (O(k)).

    Total time is O(n+k). Since it doesn't make sense to let k be more than n, it's the linear solution.

    Perl code for that:

    sub unique
    {
      my ($arr, $brr) = @_;
      my %hash = map{$_ => 1} @$arr;
      %hash{$_}-- for @$brr;
      return grep {$_} keys %hash;
    }
    

提交回复
热议问题