zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    JDK、JRE、JVM
    windows常用DOC命令
    开发Unity3D空战类插件 战机飞行模拟模板
    开发Unity3D空战类插件 现代战机武器系统
    用Unity3D开发空战游戏模板 Air Warfare
    用Unity3D开发空战游戏模板 Air Warfare Pro
    zoj1183 Scheduling Lectures
    zoj 1149 Dividing
    zoj1136 Multiple
    zoj1108 FatMouse's Speed
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7210400.html
Copyright © 2011-2022 走看看