leetcode [Contains Duplicate]//待整理多种解法

来源:互联网 发布:淘宝手机详情页宽度 编辑:程序博客网 时间:2024/06/08 15:42
public class Solution {    public boolean containsDuplicate(int[] nums) {        HashMap<Integer, Integer> map = new HashMap<>();//用map来记录数组中的元素出现的次数        for(int i = 0; i < nums.length; i++){//遍历数组,建立哈希表        if(map.containsKey(nums[i])){        map.put(nums[i], map.get(nums[i]) + 1);        }        else{        map.put(nums[i], 1);        }        }        for(int count : map.values()){//遍历map的元素出现次数的集合,若有大于等于2的就返回正确        if(count >= 2){        return true;        }        }        return false;    }}

可以不用Map,而用Set,看这个元素之前装进去没有过,则只用写一个循环

public class Solution {    public boolean containsDuplicate(int[] nums) {        Set<Integer> set = new HashSet<>();        for(int num : nums){        if(set.contains(num)){        return true;        }        else{        set.add(num);        }        }        return false;    }}

0 0
原创粉丝点击