Easy 4lines C++ code, it may faster


  • 3
    W
    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) 
        {
            int size=nums.size();
            sort(nums.begin(),nums.end());
            nums.erase(unique(nums.begin(),nums.end()),nums.end());
            return (size!=nums.size());
        }
    };

  • 0
    B
    This post is deleted!

  • 4

    Your running time is 28ms, if not use unique, it will be 24ms:

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

  • 2
    R
    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) 
        {
    	unordered_set<int> uset;
    	for(auto n: nums){
    		auto r=uset.insert(n);
    		if(!r.second)
    			return true;
    	}
    	return false;
        }
    };
    

    using some space,no sorting


  • 0
    B

    class Solution {
    public:
    bool containsDuplicate(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    return unique(nums.begin(), nums.end()) != nums.end();
    }
    };


  • 1

    sort is O(nlogn);

    And using unordered_set is O(n).


  • 0
    R

    yeah,u r right.it's a trade-off between runtime and extra-used space.just another though about the problem.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.