Find a duplicate in array of integers

后端 未结 4 1473
既然无缘
既然无缘 2021-02-07 18:22

This was an interview question.

I was given an array of n+1 integers from the range [1,n]. The property of the array is that it has k (k&

4条回答
  •  我在风中等你
    2021-02-07 19:04

    Here is a possible implementation:

    function checkDuplicate(arr) {
      console.log(arr.join(", "));
      let  len = arr.length
          ,pos = 0
          ,done = 0
          ,cur = arr[0]
          ;
      while (done < len) {
        if (pos === cur) {
          cur = arr[++pos];
        } else {
          pos = cur;
          if (arr[pos] === cur) {
            console.log(`> duplicate is ${cur}`);
            return cur;
          }
          cur = arr[pos];
        }
        done++;
      }
      console.log("> no duplicate");
      return -1;
    }
    
    for (t of [
         [0, 1, 2, 3]
        ,[0, 1, 2, 1]
        ,[1, 0, 2, 3]
        ,[1, 1, 0, 2, 4]
      ]) checkDuplicate(t);

    It is basically the solution proposed by @maraca (typed too slowly!) It has constant space requirements (for the local variables), but apart from that only uses the original array for its storage. It should be O(n) in the worst case, because as soon as a duplicate is found, the process terminates.

提交回复
热议问题