Description
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.
Solution
- 可以採用集合的特性,對於HashSet,採用Hash結構保存數據,同時確保數據不重複,在每次添加一個元素之前判斷是否已存在該數據,如果存在則說明重複了,否則把該元素添加集合裏面,直到所有元素都判斷完。
- 利用大數組來模擬元素是否出現,此方法消耗大量內存,但速度快。比如定義boolean數組data[Integer.MAX_VALUE],如果元素item出現過,則data[item] = true,對於item爲負數的情況,可考慮使用兩個數組或者元素平移。
Code
import java.util.*;
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int item : nums){
if(set.contains(item)){
return true;
} else {
set.add(item);
}
}
return false;
}
}