Contains Duplicate

来源:互联网 发布:阿里推荐算法典型特征 编辑:程序博客网 时间:2024/05/16 08:27

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;            }}
0 0
原创粉丝点击