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 }

 

转载于:https://www.cnblogs.com/DongPingAn/p/8994655.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值