Skip to content

Commit

Permalink
Create FindtheDuplicateNumber.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
priyavelu7 authored Jun 25, 2020
1 parent 7007970 commit 9e9a890
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Week 4/FindtheDuplicateNumber.cpp
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;
}
};

0 comments on commit 9e9a890

Please sign in to comment.