关闭

[leetcode] 217. Contains Duplicate

标签: leetcodeeasy
72人阅读 评论(0) 收藏 举报
分类:

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;
    }
};




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10124次
    • 积分:636
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类