LeetCode 217. Contains Duplicate(Java)

来源:互联网 发布:单片机 延时 远离 编辑:程序博客网 时间:2024/06/11 20:57

原题:
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,即数组中的元素都是唯一的。


思路:
1.利用Set集合中元素都是唯一的特点进行存储;
2.当set.add(num[i])返回false时则代表该数在set中已经存在,没有继续添加,此时方法返回true,即存在复制品;
3.如果遍历完数组没有出现复制品,则返回false。


代码:

public class Solution {    public boolean containsDuplicate(int[] nums) {        Set<Integer> set = new HashSet<Integer>();        for(int num:nums){            if(!set.add(num)){                return true;               }        }        return false;    }}
0 0
原创粉丝点击