标签:
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)
.class Solution { public: int findDuplicate(vector<int>& nums) { int n = nums.size(), slow = 0, fast = 0; do { slow = nums[slow]; fast = nums[nums[fast]]; }while(slow != fast); fast = 0; while(slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } };
// This problem can be transfromed to "Linked List Cycle" problem.
// There are two pointers, one goes one step, another goes two steps.
287. Find the Duplicate Number *HARD*
标签:
原文地址:http://www.cnblogs.com/argenbarbie/p/5340180.html