217. Contains Duplicate

来源:互联网 发布:互联网大数据技术 编辑:程序博客网 时间:2024/05/18 02:23

217. Contains Duplicate         

     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.

分析:   使用HashSet类,该类是存在于java.util包中。同时也被称为集合,该容器中只能存储不重复的对象。将数组中的元素全部存入HashSet中,若hashSet的大小等于数组的大小,则说明无重复,返回false;否则存在重复整数,返true。

class Solution {    public boolean containsDuplicate(int[] nums) {        HashSet<Integer> hashSet = new HashSet<>();for(int i = 0;i < nums.length;i++){hashSet.add(nums[i]);}if(hashSet.size() == nums.length)return false;elsereturn true;    }}