Find the Duplicate Number

题目描述

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

解题方法

find two repeating elements的方法1-4不适用,方法5可以改造到这里

  • 每经过一个元素i,就将它nums[i]设为负数
  • 这样如果下一次遇到元素j,如果nums[j]已经为负数,说明它是一个重复元素

时间复杂度 O(N) 空间复杂度 O(1)

另一种方法

另一种方法是可以将元素i放到它对应的位置index i-1去,然后不断地swap, 最后再扫一遍,对应有两个数的位置就是重复的数

Solution

class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i, num in enumerate(nums):
            if num < 0:
                x = num * -1
            else:
                x = num
            if nums[x] >= 0:
                nums[x] = nums[x] * -1
            else:
                return x