217. Contains Duplicate

来源:互联网 发布:电子书资源 知乎 编辑:程序博客网 时间:2024/06/06 03:56

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.

题目含义:
给定整数数组,查找数组是否包含任何重复项。如果数组中的任何值至少出现两次,则函数应返回true,如果每个元素都不同,则返回false。
思想:先用库函数快排排序
判断相邻的两个值是否相同
C++ AC代码:时间o(nlogn) 空间o(1)
class Solution {public:    bool containsDuplicate(vector<int>& nums) {        int len = nums.size();        sort(nums.begin(),nums.end());        bool flag = false;        for(int i=0;i<len-1;i++){            if(nums[i]==nums[i+1]){                flag = true;                break;            }        }        return flag;    }};