LeetCode:Contains Duplicate

来源:互联网 发布:xp网络共享打印机设置 编辑:程序博客网 时间:2024/06/05 03:38

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.

解题思路:

使用Java中的HashSet,其底层使用HashMap进行使用,即HashSet中的元素是不能重复的,因此可以用其来解决该题目。

代码如下:

public  boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i : nums) if(!set.add(i))// 如果集合中已经有重复的元素的话,则return true return true;  return false;}

0 0