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 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步