脚本宝典收集整理的这篇文章主要介绍了刷题-Leetcode-217. 存在重复元素,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
217. 存在重复元素
题目链接来源:力扣(LeetCode)链接:https://leetcode-cn.COM/PRoblems/contains-duplicate/
题目描述
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true
。如果数组中每个元素都不相同,则返回 false
。
示例 1:
输入: [1,2,3,1] 输出: true
示例 2:
输入: [1,2,3,4] 输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2] 输出: true
题目分析
更推荐第二种方法,一般情况下空间足够,主要是要降低@R_480_1304@。
1 class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 //检测重复 4 //set 元素唯一 5 //dictionary(java:HashMap) 每个元素出现次数 6 7 //1.排序法 8 // if(nums.length==0||nums==null){ 9 // return false; 10 // } 11 // Arrays.sort(nums);//排序最优时间O(nLOGn) 空间o(1) 12 // int prev = nums[0]; 13 // for(int i=1;i<nums.length;i++){ 14 // if(prev==nums[i]){ 15 // return true; 16 // }else{ 17 // prev = nums[i]; 18 // } 19 // } 20 // return false; 21 22 //2.set法 比较数组和set大小,相等为false 时间o(n) 空间o(n) 23 // if(nums.length==0||nums==null){ 24 // return false; 25 // } 26 // HashSet<Integer> set = new HashSet<>(); 27 // for(int num:nums){ 28 // set.add(num); 29 // } 30 // return set.size()==nums.length?false:true; 31 32 33 34 // //3.字典法(HashMap) 计算元素出现的次数 遍历value有>=1为true 空间o(n) 35 if(nums.length==0||nums==null){ 36 return false; 37 } 38 HashMap<Integer,Integer> map = new HashMap<>(); 39 for(int num:nums){ 40 if(!map.containsKey(num)){ 41 map.put(num,1); 42 }else{ 43 map.put(num,map.get(num)+1); 44 } 45 } 46 for(int k:map.keySet()){ 47 if(map.get(k)>1){ 48 return true; 49 } 50 } 51 return false; 52 } 53 }
以上是脚本宝典为你收集整理的刷题-Leetcode-217. 存在重复元素全部内容,希望文章能够帮你解决刷题-Leetcode-217. 存在重复元素所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。