LeetCode # Array # Easy # 217. Contains Duplicate

Posted dongpingan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode # Array # Easy # 217. 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.

题目:给定一个数组,判断其中有无重复元素,返回true或false。

思路:首先想到用一个hashmap存元素,遍历数组,如果在map中能查到则返回true,否则将该元素存入map。

这种方法空间复杂度较低,时间复杂度为0(N)

 1 import java.util.HashMap;
 2 
 3 class Solution {
 4     public boolean containsDuplicate(int[] nums) {
 5         HashMap<Integer, Integer> map = new HashMap<>();
 6         int n = nums.length;
 7         boolean tag = false;
 8         for(int i =0; i< n; i++){
 9             if(map.containsKey(nums[i])){
10                 tag = true;
11             }else{
12                 map.put(nums[i], 1);
13             }
14         }
15         return tag;
16     }
17 }

然后,最佳方法的思路是:先找到最大元素和最小元素,然后设置一个bool类型数组。

如果一个数num-min 的bool变量为空,则是第一次出现,将其bool变量设置成true。若不为空,则说明其为重复元素,返回true。

 1 class Solution {
 2     public boolean containsDuplicate(int[] nums) {
 3         if(nums == null || nums.length == 1) return false;  
 4         int max = Integer.MIN_VALUE;
 5         int min = Integer.MAX_VALUE;
 6         for(int num : nums){
 7             if(num > max)
 8                 max = num;
 9             if(num < min)
10                 min = num;
11         }       
12         boolean[] bool = new boolean[max - min + 1];
13         for(int num : nums){
14             if(bool[num - min])//如果这个bool值=-true,则返回true
15                 return true;
16             else
17                 bool[num - min] = true;
18         }        
19         return false;        
20     }
21 }

 

以上是关于LeetCode # Array # Easy # 217. Contains Duplicate的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode--219268283414448 Array(Easy)

LeetCode--Array--Two sum (Easy)

LeetCode # Array # Easy # 665. Non-decreasing Array

java [14。最长的共同前缀] #Array #Leetcode #Easy

java [9。回文数] #Array #Mod #Leetcode #Easy

leetcode_easy1486. XOR Operation in an Array