217. Contains Duplicate

来源:互联网 发布:plc编程员招聘 编辑:程序博客网 时间:2024/05/09 16:08

题目:

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.


我的思路:

使用Java本身的HashSet结构,根据其集合特性保证其中的值不会重复。


代码:

public class Solution {    public boolean containsDuplicate(int[] nums) {        //进行出错处理        if (nums.length == 0) return false;                //HashSet是集合,不允许出现重复的数值        HashSet<Integer> appeared = new HashSet<>();        for(int n : nums) {            if (!appeared.add(n)) return true;        }        return false;    }}

0 0
原创粉丝点击