Contains Duplicate

Description:

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.

解法一:

思路:

这里可以利用set容器,set就是数学上集合的抽象,集合是不会有重复元素的。利用set.add()方法,如果set.add()方法的值为false则代表在set中已经存在该元素了,所以整个函数返回true.如果遍历所有元素都是不一样的,最后返回false,代表数组中没有重复的元素。

Code:

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        for(int i : nums)
            if(!set.add(i))
                return true;
        return false;        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值