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.
Analyse: sort first then compare.
Runtime: 40ms.
1 class Solution { 2 public: 3 bool containsDuplicate(vector<int>& nums) { 4 if(nums.size() <= 1) return false; 5 6 sort(nums.begin(), nums.end()); 7 8 for(int i = 1; i < nums.size(); i++){ 9 if(nums[i] == nums[i - 1]) return true; 10 } 11 return false; 12 } 13 };
时间: 2024-10-07 11:02:02