zoukankan      html  css  js  c++  java
  • 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内置的排序算法时间复杂度比较低!

  • 相关阅读:
    python之模块与包
    python之异常处理
    python之os与json&pickle模块
    python之random、time与sys模块
    python之re模块
    python之匿名函数、递归与二分法
    python之内置函数
    python之迭代器、生成器及列表推导式
    python之第一对象,函数名的应用,闭包
    python之命名空间与作用域
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5103550.html
Copyright © 2011-2022 走看看