返回题库

寻找重复数

Find the Duplicate Number

专题
Algorithmic Programming / 算法编程
难度
L3
来源
Citadel

题目详情

问题:寻找重复数

考察:数组

来源:Citadel

链接:https://www.jointaro.com/interviews/questions/find-the-duplicate-number/

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and using only constant extra space.

 

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2

Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

Example 3:

Input: nums = [3,3,3,3,3]
Output: 3

 

Constraints:

  • 1 <= n <= 105
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.

 

Follow up:

  • How can we prove that at least one duplicate number must exist in nums?
  • Can you solve the problem in linear runtime complexity?
解析

思路:把数组值看作从下标指向下一个下标的函数,重复数会形成环入口。使用 Floyd 快慢指针先相遇,再从起点和相遇点同步前进找到环入口。

复杂度:时间 O(n),空间 O(1),且不修改数组。