LeetCode每日一题:存在重复元素(No.217)

188 阅读1分钟

题目:存在重复元素


给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例:


 输入: [1,2,3,1]
 输出: true
 
 输入: [1,2,3,4]
 输出: false
 
 输入: [1,1,1,3,3,4,3,2,4,2]
 输出: true

思考:


这道题可以使用Map或者Set来解决,这样比较简单。遍历数组,将元素加入集合可以解决。

实现:


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