leetcode 217

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.

题意:判断数组中是否有重复的元素,如果没有返回false,反之返回true.

解法:先对数组进行排序,然后比较排序之后数组相邻元素。

代码如下:

 

 1 class Solution {
 2 public:
 3     bool containsDuplicate(vector<int>& nums) {
 4         int size = nums.size();
 5         if(size == 0 || size == 1)
 6         {
 7             return false;
 8         }
 9         sort(nums.begin(), nums.end());
10         for(int i = 1; i < nums.size(); i++)
11         {
12             if(nums[i-1] == nums[i])
13             {
14                 return true;
15             }
16         }
17         return false;
18     }
19 };

 

posted @ 2016-12-18 20:50  花椰菜菜菜菜  阅读(204)  评论(0编辑  收藏  举报