LeetCode(217):Contains Duplicate

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,遍历该数组,将值逐个放入HashMap,如果在遍历的过程中出现值存在HashMap的Keys中则返回True;(2)将数组排序,判断相邻两个元素之间是否相同,如果相同返回True。

Code:

//思路(1)利用HashMap
public boolean containsDuplicate(int[] nums) {
        int len = nums.length;
        HashMap<Integer, Integer> counter = new HashMap<Integer,Integer>();
        for(int i=0;i<len;i++){
            if(!counter.containsKey(nums[i])){
                counter.put(nums[i], 1);
            }else{
                return false;
            }
        }
        return true;
        
    }
//思路(2)排序
public boolean containsDuplicate(int[] nums) {
         if (nums.length <= 1) {
            return false;
        }
         
        Arrays.sort(nums);
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                return true;
            }
        }
        return false;    
    }

提交结果显示思路(2)比较好一点,猜测因为Java内置的排序算法时间复杂度比较低!

原文地址:https://www.cnblogs.com/Lewisr/p/5103550.html