[Wins the offer] does not modify the array to find duplicate numbers

Do not modify the array to find duplicate numbers

topic

Given a length of the n + array nums 1, all the numbers in the array are within the scope 1~n, wherein n≥1.

Look for a repeat of the array in any number, but can not modify the input array.

Sample

Given nums = [2, 3, 5 , 4, 3, 2, 6, 7].
Back to 2 or 3.

Questions: If you can only use the extra space is O (1), which is how to do it?

answer

Unordered_map count using the method, to determine whether there are duplicate numbers list

class Solution {
public:
    int duplicateInArray(vector<int>& nums) {
        unordered_map<int, int> umap;
        for (int i = 0; i < nums.size(); i ++) {
            if (umap.count(nums[i])) 
                return nums[i];
            umap[nums[i]] = 1;
        }
        return -1;
    }
};
Published 10 original articles · won praise 0 · Views 568

Guess you like

Origin blog.csdn.net/weixin_44922845/article/details/104097981