赞
踩
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.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
包含有n+1个不大于n的正整数的数组一定存在重复元素,本题要求从这样的数组中找出重复的那个元素。题目很简单,有很多方法可做,但是难在要求空间复杂度O(1),时间复杂度小于O(n2),并且源数组是只读的,不允许任何修改操作。这样就限制了诸如Hash表,排序等的解法。最优解法是采用弗洛伊德循环寻找算法,原理如下:
i | 0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|---|
A[i] | 1 | 3 | 4 | 2 | 2 |
如果这样的数组中出现重复元素,那么这个链表就会出现一个环
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。