Contains Duplicates

题目:

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

分析:

可以用排序做 O(nlogn)

可以用哈希表做 O(n)

通过这道题学会一个道理 unordered_map和map可以用hash[a] = 1这样的方法赋值, unordered_set只能用hash.insert()

解法1:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if (nums.size() < 2) {
            return false;
        }

       unordered_set<int> hash;
        for (int i = 0; i < nums.size(); i++) {
            if (hash.find(nums[i]) != hash.end() ) {
                return true;
            }
            hash.insert(nums[i]);
        }
        return false;
    }
};

解法2:排序方法

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

results matching ""

    No results matching ""