-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7007970
commit 9e9a890
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
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 | ||
*/ | ||
class Solution { | ||
public: | ||
int findDuplicate(vector<int>& nums) { | ||
int slow=0,fast=0; | ||
while(fast<nums.size()&&nums[fast]<nums.size()){ | ||
slow=nums[slow]; | ||
fast=nums[nums[fast]]; | ||
if(slow==fast) break; | ||
} | ||
slow=0; | ||
while(slow!=fast){ | ||
slow=nums[slow]; | ||
fast=nums[fast]; | ||
} | ||
return fast; | ||
} | ||
}; |