题目:
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:
O(n2)
.链接: http://leetcode.com/problems/find-the-duplicate-number/
题解:
很有意思的一道题目。 一开始就想到了Brute Force, 自然是O(n2)的Complexity,不满足题意。 后来看了Discuss和其中的一些资料,发现可以像Linked List Cycle II一样,用快慢指针来解决。非常巧妙。据传说这道题费了knuth大约24小时才解决...未验证,不过很有意思。 也有O(nlogn)的binary search解法,很比较巧妙。
Time Complexity - O(n), Space Complexity - O(1)
public class Solution { public int findDuplicate(int[] nums) { if(nums == null || nums.length < 2) { return -1; } int slow = nums[0], fast = nums[nums[0]]; while(slow != fast) { slow = nums[slow]; fast = nums[nums[fast]]; } slow = 0; while(slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } }
Reference:
http://keithschwarz.com/interesting/code/?dir=find-duplicate
https://leetcode.com/discuss/61514/understood-solution-space-without-modifying-explanation
https://leetcode.com/discuss/60830/solutions-explanation-space-without-changing-input-array
https://leetcode.com/discuss/61086/java-time-and-space-solution-similar-find-loop-in-linkedlist
https://leetcode.com/discuss/60852/ac-c-code-with-o-n-time-and-o-1-space
https://leetcode.com/discuss/64637/java-o-1-space-using-binary-search
https://leetcode.com/discuss/62696/tortoise-%26-haire-cycle-detection-algorithm
https://leetcode.com/discuss/69766/share-my-solution-o-n-time-o-1-space-12-ms
https://leetcode.com/discuss/60990/o-n-time-o-1-space-using-floyds-loop-detection
https://leetcode.com/discuss/60878/a-java-solution-o-n-time-and-o-1-space
https://leetcode.com/discuss/68441/simple-c-code-with-o-1-space-and-o-nlogn-time-complexity
https://leetcode.com/discuss/61179/short-versions-binary-search-solution-nlogn-pointer-detection
287. Find the Duplicate Number
原文:http://www.cnblogs.com/yrbbest/p/5040706.html