Java [Leetcode 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.

解题思路:

这种重复的问题首先想到的就是Set了。

代码如下:

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

  

原文地址:https://www.cnblogs.com/zihaowang/p/5072007.html