Leetcode - Contains Duplicate

Question

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.


Java Code

//版本一:使用HashSet容器存儲已經遍歷過的數組元素
public boolean containsDuplicate(int[] nums) {
    int len = nums.length;
    HashSet<Integer> set = new  HashSet<>(2*len);
    for(int i = 0 ; i < len; ++i) {
        if(!set.add(nums[i]))
            return true;
    }

    return false;
}

//版本二:先對數組排序,再逐位比較相鄰元素是否相等
public boolean containsDuplicate2(int[] nums) {
    Arrays.sort(nums);
    int len = nums.length - 1;
    for(int i = 0 ; i < len; ) {
        if(nums[i] == nums[++i])
            return true;
    }

    return false;
}
發佈了74 篇原創文章 · 獲贊 24 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章