Asked 1 year ago
0Comments
6 Views
LEETCODE !nums. The array contains n + 1 integers. n is 5. This means the array should have 6 numbers, and those numbers can only be between 1 and 5.int findDuplicate(vector<int>& nums) {
sort(nums.begin(),nums.end());
for(int i = 0 ; i<nums.size()-1 ; i++){
if(nums[i] == nums[i+1]){
return nums[i] ;
}
}
return -1 ;
}class Solution {
public:
int findDuplicate(vector<int>& nums) {
int answerIndex = -1 ;
for( int i = 0 ; i < nums.size() ; i++){
int currentIndex = abs(nums[i]) ;
//Already Visited
if(nums[currentIndex] < 0){
return currentIndex ;
}
//mark it as Negative !
nums[currentIndex] *= -1 ;
}
return answerIndex ;
}
};
// Second one is Better Approch !
answerIndex is initialized to -1. This variable is used to store the index of the duplicate number if found.Initialization:
int answerIndex = -1;
answerIndex is initialized to -1. This variable is used to store the index of the duplicate number if found.Iterating Through the Array:
for (int i = 0; i < nums.size(); i++) nums array.Accessing the Absolute Value of Current Element:
int currentIndex = abs(nums[i]);currentIndex is assigned the absolute value of the current element in nums. This is necessary because we might have already marked some elements as negativeChecking if the Element at currentIndex is Already Visited:
if (nums[currentIndex] < 0) {
return currentIndex;
}
currentIndex is negative, it means this index has been visited before, indicating a duplicate. Hence, currentIndex is returned as the duplicate number.Marking the Element as Visited:
nums[currentIndex] *= -1;
currentIndex is not negative, we mark it as visited by multiplying it by -1, making it negative.Returning the Result:
return answerIndex;
answerIndex is returned, which is -1. However, in the context of the problem, there will always be a duplicate, so this line should theoretically never execute.FINALLY !Consider the array [1, 3, 4, 2, 2].
[1, 3, 4, 2, 2]currentIndex = abs(nums[0]) = abs(1) = 1nums[1] as negative: [1, -3, 4, 2, 2]currentIndex = abs(nums[1]) = abs(-3) = 3nums[3] as negative: [1, -3, 4, -2, 2]currentIndex = abs(nums[2]) = abs(4) = 4nums[4] as negative: [1, -3, 4, -2, -2]currentIndex = abs(nums[3]) = abs(-2) = 2nums[2] as negative: [1, -3, -4, -2, -2]currentIndex = abs(nums[4]) = abs(-2) = 2nums[2] is negative, it means we've seen this index before.currentIndex = 2 as the duplicate number.Read Again :) Start by setting a default answer:
answerIndex to -1.Loop through each element in the array:
Find the index that corresponds to the current element:
Check if the element at this index has been visited before:
Mark the index as visited:
-1.Return the duplicate number if found:
Share