LeetCode刷题笔记:存在重复

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.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

解题思路

又一次理所当然的想着来个双层循环遍历,结果一测试,果不其然超时:

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

        for(int i = 0; i < size - 1; ++i) {
            for(int j = i + 1; j < size; ++j) {
                if(nums[i] == nums[j]) return true;
            }
        }
        return false;
    }
};

Solution

尝试一下先将数组排序,排序之后再遍历:

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

这样的方法战胜了96.85%的提交记录,但是我们还是要学习别人的解法:
使用集合来减少搜索的范围:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int>visited;
        for(int i=0;iif(visited.find(nums[i])==visited.end())
                visited.insert(nums[i]);
            else{
                return true;
            }
        }
        return false;

    }
};

你可能感兴趣的:(LeetCode刷题笔记,LeetCode刷题笔记)