leetcode 217 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算法

思路

  • 這道題理解起來比較簡單,首先仍是要注意一下邊界條件/異常輸入,對於長度小於等於1的數組作一個直接的返回
  • 對於這種要考慮數組中元素的重複的問題,就很容易想到hashmap,key就是元素的值,value能夠表示元素的個數,對於已經存在的key,直接返回true,可是這種解法須要額外O(n)的空間
  • 在使用hashmap求解的過程當中,我意識到了這個方法仍是想的複雜了,數組元素的重複性問題一般還有一種思路就是數組的預排序
  • 先對輸入數組進行預排序,而後只須要比較數組和它相臨的元素是否相等就能夠了

解法一 HashMap

public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if(length <= 1){
            return false;
        }     
        HashMap<Integer,Integer> count = new HashMap<Integer, Integer>();
        count.put(nums[0], 1);
        
        for(int i = 1;i<nums.length;i++){
            int tempKey = nums[i];
            if(count.get(tempKey) != null ){
                return true;
            }else{
                count.put(tempKey, 1);
            }
        }
        
        return false;
    }

解法二 預排序算法

public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if(length <= 1){
            return false;
        } 
        Arrays.sort(nums);
        for(int i=0 ;i<length-1;i++){
            if(nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }
相關文章
相關標籤/搜索