【Leetcode Algorithm】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.

代碼:

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        boolean flag = false;
        HashMap hm = new HashMap();
        for(int i=0; i<nums.length; i++){
            if(!hm.containsKey(nums[i])){
                hm.put(nums[i],1);
            }
            else{
                flag = true;
                break;
            }
        }
        return flag;
    }
}


注意:
1、數組a求長度用a.length,而不是a.length()
2、本題用HashMap來做會很簡單。只要將數組中的數當鍵值key,出現的次數當value,當發現數組中包含某個鍵值key時,說明有重複,則直接跳出循環。


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