Created
October 7, 2022 19:24
-
-
Save webber2408/39bcb8e7a63cbf4d82fbdab081ca517f to your computer and use it in GitHub Desktop.
Approach-3) Find Duplicates - Negative Marking
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
class Solution { | |
public: | |
int findDuplicate(vector<int>& nums) { | |
for(int i=0; i<nums.size(); i++){ | |
int absNum = abs(nums[i]); | |
if(nums[absNum] < 0){ | |
// Number is duplicate | |
return absNum; | |
} | |
nums[absNum] = -nums[absNum]; | |
} | |
for(int i=0; i<nums.size(); i++){ | |
if(nums[i] < 0) nums[i] = -nums[i]; | |
} | |
return -1; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment