zoukankan      html  css  js  c++  java
  • LeetCode 219. Contains Duplicate II (包含重复项之二)

    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.


    题目标签:Array, Hash Table

      题目给了我们一个nums array 和一个 k, 让我们找到两个 相同的项,并且它们的index 差值 小于等于 k。

      这次我们依然要利用Hash Table,因为这次需要比较它们的index, 所以需要key 和value, 不同于 包含重复项之一 那一题,只需要比较数字。

      遍历nums array, 如果nums[i] 不在hash table 里的话,就把 nums[i] 当作key,  i 当作 value 存入hash table;

               如果hash table 有nums[i]的话,就比较两个index 的差值,如果小于等于 k, 就返回true。

    Java Solution:

    Runtime beats 52.19% 

    完成日期:05/27/2017

    关键词:Array, Hash Table

    关键点:利用Hash Table, 把nums[i] 当作key, i 当作value 存入Hash Table

     1 public class Solution 
     2 {
     3     public boolean containsNearbyDuplicate(int[] nums, int k) 
     4     {
     5         if(nums.length == 0 || nums == null)
     6             return false;
     7         
     8         HashMap<Integer, Integer> unique = new HashMap<>();
     9     
    10         for(int i=0; i<nums.length; i++)
    11         {
    12             if(unique.containsKey(nums[i]) && i - unique.get(nums[i]) <= k)
    13             {    
    14                 return true;
    15             }
    16             else
    17                 unique.put(nums[i], i);
    18         }
    19         
    20         
    21         return false;
    22     }
    23 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    每次任务 创建 一个 Scheduler,运行完直接shutdown ,同时运行不相互影响.
    get 和 post 的区别
    jq ajax
    h5
    reset
    ajax
    手机端
    IE浏览器下LI的默认高度
    IE FF 支持li:hover,但是ie6不支持,a:hover ul 这种写法是要搭配顶部针对IE6声明用的
    ie7/8卸载工具 降级到IE6
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7487907.html
Copyright © 2011-2022 走看看