by Utkarsh Jaiswal
Technology
November 21, 2023
|
6 min read
Example:
Input: nums = [1, 2, 3, 1]
Output: true
One way to address this problem is by utilizing a sorting approach. The idea is to sort the array and check if any element in the ith position is equal to the element in the i+1th position. If a match is found, the function returns true.
class Solution { public: bool containsDuplicate(vector<int>& nums) { std::sort(nums.begin(), nums.end()); bool hasDuplicate = false; for (int i = 0; i < nums.size() - 1; ++i) { if (nums[i] == nums[i + 1]) { hasDuplicate = true; break; } } return hasDuplicate; } };
Another efficient approach involves using a hash map. In this method, we iterate through the array, checking if the current element already exists in the hash map. If it does, we return true; otherwise, we mark the element in the hash map. This approach has a linear time complexity.
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, int> umap; for(int i = 0; i < nums.size(); i++){ if(umap[nums[i]] != 0){ return true; } else { umap[nums[i]] = 1; } } return false; } };