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;
        }
    
     }

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

    版权声明:本文为博主原创文章,未经博主允许不得转载。
  • 相关阅读:
    Jmeter非GUI模式运行脚本
    vmware下 linux如何扩展磁盘空间
    (完美解决方案)Windows Server 2012 R2报错:无法启动此程序,因为计算机中丢失 apimswincrtstdiol110.dll 解决
    Python程序执行性能优化心得
    jmeter中TPS和吞吐量区别与联系
    Python多进程之Pool进程池浅析
    为什么Jmeter 运行时到达持续时间不停止?
    一些在线实用小工具
    笔记20171225
    JMeter 安装 linux平台
  • 原文地址:https://www.cnblogs.com/kevincong/p/7887597.html
Copyright © 2011-2022 走看看