算法第十五週作業01

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

  1. 可以採用集合的特性,對於HashSet,採用Hash結構保存數據,同時確保數據不重複,在每次添加一個元素之前判斷是否已存在該數據,如果存在則說明重複了,否則把該元素添加集合裏面,直到所有元素都判斷完。
  2. 利用大數組來模擬元素是否出現,此方法消耗大量內存,但速度快。比如定義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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章