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;
    }
相关文章
相关标签/搜索