217. Contains Duplicate

xiaoxiao2021-02-28  163

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存储出现过的元素。在循环中,如果set里包含了当前元素,则返回ture,如果不包含,则将当前元素存入set。

public class Solution { public boolean containsDuplicate(int[] nums) { if(nums.length==0) return false; Set<Integer> set =new HashSet<>(nums.length); for(int num:nums){ if(set.contains(num)){ return true; }else{ set.add(num); } } return false; } }另外,HashSet和HashMap的区别:

转载请注明原文地址: https://www.6miu.com/read-17911.html

最新回复(0)