• LeetCode & Q219-Contains Duplicate II


    Array Hash Table

    Description:

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

    本来继续沿用I里的HashSet,奈何用的不熟,不会用....

    用了HashMap,发现网上很多人跟我用的一样,明明是通过不了的,也不知道他们是怎么通过的....

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            if (nums.length <= 0)
                return false;
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(nums[i])) {
                    int j = map.get(nums[i]);
                    if (i - j <= k) 
                        return true;
                } else {
                    map.put(nums[i], i);
                }
            }
            return false;
        }
    }
    

    测试用例:[1,0,1,1] 1 无法通过

    参考了HashSet方法,设置了一个长度为k的窗口,通过移动窗口来确定是否满足条件,好机智!

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            Set<Integer> set = new HashSet<Integer>();  
            int start = 0, end = 0;
            for(int i = 0; i < nums.length; i++) {
                if(!set.contains(nums[i])) {    
                    set.add(nums[i]);   
                    end++;
                } else { 
                    return true;
                }
            
                if(end - start > k) {    
                    set.remove(nums[start]);
                    start++;
                }  
            }  
            return false;
        }
    }
    
  • 相关阅读:
    MessageFormat理解,MessageFormat.format(Object obj)方法
    正则表达式
    数字处理类
    包装类
    遍历Map的4种方法(来自网络)
    集合类
    数组
    字符串
    语言基础
    Linux下使用openssl加解密
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7210400.html
Copyright © 2020-2023  润新知