[leetcode] 217. 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.


Solution:

Idea: sort numbers first, and than check consecutive elements. However, the complexity of sorting depends on sorting algorithm.

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

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




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51535979
文章标签: leetcode easy
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[leetcode] 217. Contains Duplicate

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭