首页 > 其他 > 详细

287. Find the Duplicate Number

时间:2015-12-12 06:59:25      阅读:353      评论:0      收藏:0      [点我收藏+]

题目:

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.

链接: 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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!