Idea:
We can use map to do this problem. It will be very simple. Just record the number of each element directly, and then loop over and find the elements with a number greater than 1; then there is a better way to Operate on the original array. According to the meaning of the question, we know that this array consists of n elements and the range of each element is 0 - (n-1), so we can use the in-place replacement method:
The general idea of the in-place replacement method is that because the given array is in the range of 0-n-1, for example, if nums[0] is assumed to be 2, then we can put it in the position of 2, so that once we encounter duplication
If there is a collision in the same position, we can detect the repeated number; if there is no repeated number, then after the normal sorting, the number i should be at the position of the subscript i, so the idea is to scan the array again and encounter If the number with subscript i is not i, (assuming it is m), then we will exchange it with the number with subscript m. In the exchange process, if there is a repeated number, then terminate and return ture
Code 1:
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
unordered_set<int> st;
for(auto &i:nums){
if(st.find(i)!=st.end()){
return i;
}
st.insert(i);
}
return 1;
}
};
Code 2:
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
int ans;
bool flag=false;
for(int i=0;i<nums.size();++i){
while(nums[i]!=i){
if(nums[i]==nums[nums[i]]){
ans = nums[i];
flag = true;
break;
}
int temp = nums[i];
nums[i] = nums[temp];
nums[temp] = temp;
}
if(flag) break;
}
return ans;
}
};