存在重复的元素

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14127491.html

存在重复的元素

题目链接: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

题解

思路:利用哈希表,数组中的元素当成key,个数当成value。

代码

class Solution {
    public boolean containsDuplicate(int[] nums) {
       if(nums.length==0)
       return false;
       Map <Integer,Integer> map=new HashMap();
       for(int i=0;i<nums.length;i++)
       {
           Integer len=map.get(nums[i]);
           if(len==null)
               map.put(nums[i],1);
            else
               map.put(nums[i],++len);   
       }
      for(int i=0;i<map.size();i++){
          if(map.get(nums[i])>1)
             return true;
      }
      return false;
    }
}

结果

 备注

哈希和二叉树做题都是有一定的套路的呢,明天做总结。

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14127491.html