leetcode解题报告(18):Contains Duplicate

描述

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.

分析

先排个序,然后判断当前元素和下一元素是否相等就行了。

代码如下:

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

讨论区发现了一行代码写出来的:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        return nums.size() > set<int>(nums.begin(),nums.end()).size();
    }
};
posted @ 2017-05-08 22:33  larryking  阅读(150)  评论(0编辑  收藏  举报