前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关关的刷题日记05 —— Leetcode 219. Contains Duplicate II

关关的刷题日记05 —— Leetcode 219. Contains Duplicate II

作者头像
WZEARW
发布2018-04-08 17:12:43
6170
发布2018-04-08 17:12:43
举报
文章被收录于专栏:专知专知

关小刷刷题06 – 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.

方法

和217. Contains Duplicate 的区别是这个题目要求i和j的距离不能超过k.那么217中的方法1就没法用了,可以采用方法2的思路,不同的是需要用哈希表来标记,value存对应元素的下标,用来判断距离是否不超过k. 时间复杂度O(n).

代码语言:javascript
复制
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
       unordered_map<int, int>m;
        for(int i=0; i<nums.size(); i++)
        {
            if(m.find(nums[i])!=m.end() && i-m[nums[i]]<=k)
                return true;
            m[nums[i]]=i;
        }
        return false;
    }
};

活到老,学到老,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang),并注明加到Leetcode刷题。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-09-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 关小刷刷题06 – Leetcode 219. Contains Duplicate II
    • 题目
      • 方法
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档