Offer] [prove safety questions plane array 03. duplicate numbers

topic

Find an array duplicate numbers.
All numbers in an array of length nums n's are in the range of 0 ~ n-1. Some digital array is duplicated, but do not know how many numbers repeat, do not know each number was repeated several times. Please find an array of any one of the duplicate numbers.
Example 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 

limit:
2 <= n <= 100000

A thought: hash table

Initializing the hash table size is the size of the array elements, the initial value of -1 (because all of the elements in the array is greater than 0).
Each number n through the array, if the hash value of 0 indicates that the number already exists, returns directly; otherwise, update the number n corresponding to the hash value of 0 indicates a position already exists.

Code

Time complexity: O (n)
space complexity: O (n)

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        vector<int> hash(nums.size(), -1);
        for (auto n : nums) {
            if (hash[n] == 0) return n;
            ++hash[n];
        }
        return -1;
    }
};

Thinking two: Sort Find

After ordering, if there are equal numbers of two adjacent return.

Code

Time complexity: O (nlogn)
Complexity Space: O (1)

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i] ==  nums[i - 1]) return nums[i];
        }
        return -1;
    }
};

Thinking three: exchange position

Subscript i is the position of each array, it is determined whether or equal to the nums [i]

  • If the index i is not equal position nums [i], then the nums [i] should actually be placed nums [nums [i]] position
    • If nums [i] equal nums [nums [i]], the repeating elements found;
    • Otherwise, the exchange nums [i] and nums [nums [i]], soon nums [i] in the correct position.
  • If they are equal, it is determined that a position.

Code

Time complexity: O (n)
complexity of space: O (1)

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        for (int i = 0; i < nums.size(); ++i) {
            while (nums[i] != i) {
                if (nums[nums[i]] == nums[i]) return nums[i];
                swap(nums[i], nums[nums[i]]);
            }
        }
        return -1;
    }
};
Published 18 original articles · won praise 86 · views 160 000 +

Guess you like

Origin blog.csdn.net/u013178472/article/details/104968711