zoukankan      html  css  js  c++  java
  • leetCode-Contains Duplicate

    Description:
    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.

    My Solution:

    class Solution {
        public boolean containsDuplicate(int[] nums) {
            Map<Integer,Integer> map = new HashMap<Integer,Integer>();
            int len = nums.length;
            for(int i = 0;i < len;i++){
               map.put(nums[i],(map.get(nums[i]) == null)?1:map.get(nums[i])+1);
            }
            for(Integer key : map.keySet()){
                if(map.get(key) > 1){
                    return true;
                }
            }
            return false;
        }
    }

    Better Solution 1:

    //数组排序后判断相邻元素是否相等
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; ++i) {
            if (nums[i] == nums[i + 1]) return true;
        }
        return false;
    }

    Better Solution2:

    //用到set的contains和add
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>(nums.length);
        for (int x: nums) {
            if (set.contains(x)) return true;
            set.add(x);
        }
        return false;
    }

    Best Solution:

    //先求出nums数组的最小值min和最大值max,然后新建boolean数组,下标为最小值到最大值之间的所有元素,遍历nums,如果一个元素j出现,将boolean数组(j - min)下标对应的值设置为true,如果下次遍历到j,那么返回true
    class Solution {
        public boolean containsDuplicate(int[] nums) {
            if (nums.length <= 1) return false;
            int minNum = nums[0];
            int maxNum = nums[0];
            for (int num : nums) {
                if (minNum > num) {
                    minNum = num;
                }
                if (maxNum < num) {
                    maxNum = num;
                }
            }
            if (maxNum == minNum) return true;
            boolean[] visit = new boolean[maxNum - minNum + 1];
            for (int num : nums) {
                int idx = num - minNum;
                if (visit[idx]) {
                    return true;
                } else {
                    visit[idx] = true;
                }
            }
            return false;
        }
    
     }

    总结:一个还是要看元素排列的规律(排序后判断相邻元素是否相等的方法),还有就是数组元素出现次数这种问题一般都能设置一个以对应元素为下标的数组用来计算出现次数。

    版权声明:本文为博主原创文章,未经博主允许不得转载。
  • 相关阅读:
    轻节点如何验证交易的存在
    梯度爆炸/消失与初始化参数
    归一化能够加速训练的原因
    正则化可以防止过拟合的原因
    关于周志华《机器学习》中假设空间规模大小65的计算
    linux学习0001
    目标检测算法
    opencv安装与卸载
    前端学习02
    前端学习01
  • 原文地址:https://www.cnblogs.com/kevincong/p/7887597.html
Copyright © 2011-2022 走看看