Distinguishing extra element from two arrays?

后端 未结 19 680
爱一瞬间的悲伤
爱一瞬间的悲伤 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:29

    Here's some simple pseudocode for a solution. I'm assuming it's OK to modify the arrays and that arrays have a remove(value) method (or that you could write one trivially). It takes the 2 arrays and returns an array containg 2 values, the first is the unique value from the first array and the second is the unique value from the 2nd array.

    function findUnique(a:Array, b:Array):Array {
      var uniqueFromA:int;
      var uniqueFromB:int;
    
      for each(value:int in a) {
        var len:int = b.length;
        b.remove(value);
        /* b's length didn't change, so nothing was removed, so the value doesn't
         * exist in it. */
        if(b.length == len) {
          uniqueFromA = value;
        }
      }
    
      /* Only the unique value in b still exists in b */
      uniqueFromB = b[0];
    
      return [uniqueFromA, uniqueFromB];
    }
    

提交回复
热议问题