题目描述:
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
Java代码实现:
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://leetcode.com/problems/contains-duplicate/