Find a duplicate in array of integers

后端 未结 4 1469
既然无缘
既然无缘 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:16

    If you are allowed to non-destructively modify the input vector, then it is pretty easy. Suppose we can "flag" an element in the input by negating it (which is obviously reversible). In that case, we can proceed as follows:

    Note: The following assume that the vector is indexed starting at 1. Since it is probably indexed starting at 0 (in most languages), you can implement "Flag item at index i" with "Negate the item at index i-1".

    1. Set i to 0 and do the following loop:
      1. Increment i until item i is unflagged.
      2. Set j to i and do the following loop:
        1. Set j to vector[j].
        2. if the item at j is flagged, j is a duplicate. Terminate both loops.
        3. Flag the item at j.
        4. If j != i, continue the inner loop.
    2. Traverse the vector setting each element to its absolute value (i.e. unflag everything to restore the vector).

提交回复
热议问题