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.
分析:先把数组排个序,然后遍历排序后的数组,查看相邻元素是否有重复,时间复杂度O(nlogn)。
class Solution { public: bool containsDuplicate(vector<int>& nums) { if( (nums.size() == 0) || (nums.size() == 1) ) return false; std::sort(std::begin(nums), std::end(nums)); //sort()是c++、java里对数组的元素进行排序的方法,包含于头文件algorithm。 for(int i = 0; i < nums.size()-1; i++) if(nums[i] == nums[i+1]) return true; return false; } };
其他解法:(集和多集的区别是:set支持唯一键值,set中的值都是特定的,而且只出现一次;而multiset中可以出现副本键,同一值可以出现多次。)
class Solution { public: bool containsDuplicate(vector<int>& nums) { set<int> s(nums.begin(), nums.end()); if (nums.size() == s.size()) return false; else return true; } };
或者:
class Solution { public: bool containsDuplicate(vector<int>& nums) { vector <bool> vec; vec.push_back(false); if (nums.size()<=1){ return false; } for (int i=0; i<nums.size();i++){ int m=nums[i]; if (m>=vec.size()){ for (int j=vec.size();j<=m;j++){ vec.push_back(false); } } if (m<vec.size()){ if (vec[m]==true){ return true; } else{ vec[m]=true; } } } return false; } };
或:sort the vector then traverse to find whether there are same value element continuesly:
class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); if (nums.size() == 0){ return false; } vector<int>::iterator it = nums.begin(); int temp = *it; it++; for (; it != nums.end(); it++){ if (*it == temp){ return true; } temp = *it; } return false; } };
或: step 1 Sort the vector
step2 use erase to remove the duplicate and compare the size of the vector
class Solution { public: bool containsDuplicate(vector<int>& nums) { int pre = nums.size(); sort(nums.begin(), nums.end()); nums.erase(unique(nums.begin(), nums.end()), nums.end()); int post = nums.size(); return (post == pre) ? false : true; return false; } };
或:use hash map
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, int> hash; vector<int>::iterator it = nums.begin(); for (; it != nums.end(); it++){ if (hash.find(*it) != hash.end()){ return true; } hash[*it] = 1; } return false; } };
时间: 2024-10-06 20:00:39