LeetCode 217. Contains Duplicate
原题链接在这里:https://leetcode.com/problems/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.
题解:
判断有没有重复,很多时候都是用HashSet, HashMap.
Tiem Complexity: O(n), n = nums.length. Space: O(n).
AC Java:
1 public class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 Set<Integer> hs = new HashSet<Integer>(); 7 for(int i = 0; i<nums.length; i++){ 8 if(hs.contains(nums[i])){ 9 return true; 10 }else{ 11 hs.add(nums[i]); 12 } 13 } 14 return false; 15 } 16 }
AC C++:
1 class Solution { 2 public: 3 bool containsDuplicate(vector<int>& nums) { 4 unordered_set<int> set; 5 for(int& num : nums){ 6 if(!set.insert(num).second){ 7 return true; 8 } 9 } 10 11 return false; 12 } 13 };