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 }

 

posted @ 2018-05-05 14:31  何以解忧,唯有撸代码  阅读(99)  评论(0编辑  收藏  举报