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

  • 相关阅读:
    Integer vs int
    j2ee gradle构建
    ubuntu16.04更新node.js
    阿里云centos7服务器
    使用jdbc给一张表增加多行字段
    安装mysql后,java使用jdbc连接mysql数据库
    关于异常try{}catch(){}
    计算机基础单位
    java mongodb 增删改查 工具类
    java 操作mongodb查询条件的常用设置
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7487907.html
Copyright © 2011-2022 走看看