LeetCode: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.

給出一個整數數組,確定數組中是否包含重複的元素,若有任何一個元素重複,返回true,否則返回false.

解題思路:

使用Java中的HashSet,其底層使用HashMap進行使用,即HashSet中的元素是不能重複的,因此可以用其來解決該題目。

代碼如下:

public  boolean containsDuplicate(int[] nums) {
		 Set<Integer> set = new HashSet<Integer>();
		 for(int i : nums)
			 if(!set.add(i))// 如果集合中已經有重複的元素的話,則return true
				 return true; 
		 return false;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章