leetcode 217
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };
以上是关于leetcode 217的主要内容,如果未能解决你的问题,请参考以下文章