ContainsDuplicate

来源:互联网 发布:java 淘淘商城 编辑:程序博客网 时间:2024/05/21 22:49

问题描述:

检测一个数组中是否含有相同元素


解决:因为set中不可添加重复元素的特性,我们可以用set来保存遍历过的元素,一旦set添加新元素失败,表明新元素与已有元素重复。


/* * 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. */import java.util.HashSet;import java.util.Set; public class ContainsDuplicate {    public boolean containsDuplicate(int[] nums) {        if(nums == null||nums.length==0)                return false;        Set<Integer> set = new HashSet<Integer>();        for(int i:nums) {                if(!set.add(i))                        return true;        }        return false;    }}


原创粉丝点击