217. Contains Duplicate
Easy
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.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> ns; for(auto n:nums){ if(ns.count(n)>0) return true; ns.insert(n); } return false; } }; class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); for(int i=0; i<int(nums.size()-1); ++i){ if(nums[i]==nums[i+1]) return true; } return false; } }; class Solution { public: bool containsDuplicate(vector<int>& nums) { int lb = INT_MAX, ub = INT_MIN; for(auto n:nums){ lb = min(n, lb); ub = max(n, ub); } int N = ub-lb+1; bool mask[N]; memset(mask, false, N*sizeof(bool)); for(auto n:nums){ if(mask[n-lb]) return true; else mask[n-lb] = true; } return false; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(nums.length); for(int i : nums) { if(set.contains(i)) return true; set.add(i); } return false; } } |
No comments:
Post a Comment