描述

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.

分析

我的想法是:遍历该数组,并判断当前元素之后有没有和该元素相等的元素,如果有,就通过distance得到这两个值之间的长度,如果小于等于k,则返回true,否则继续遍历。

代码如下:

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.size() == 0)return false;
if(k <= 0)return false;
for(auto it = nums.begin(); it != nums.end(); ++it){
if(it + 1 == nums.end())return false;
auto f = find(it + 1,nums.end(),*it);
if(f != nums.end()){
if(distance(it,f) <= k)return true;
}
}
return false;
}
};

然而测试用例中最后一个数组超时了,没ac,想了一会儿后还是不知道怎么优化这个解法,于是看了下讨论区:

https://discuss.leetcode.com/topic/15012/share-my-easy-to-understand-c-code

代码看到就懂了,还是用unordered_map,以元素值为key,元素下标为value。 遍历该数组,如果该元素不在数组中,就把元素放到这个unordered_map里。否则,判断当前元素下标与map中该元素的下标之差是否小于等于k,如果是,返回true。

代码如下:

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.size() == 0)return false;
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;
}
};

我的解法和上述解法在复杂度上相比,主要是多了distance这个函数。不过影响复杂度的主要因素是find函数。

为了查找一个范围内的值,我调用的是stl里的find函数,而这个算法的性能会略低于map自己的find函数。此外,unordered_map的一些操作的复杂度也确实低于vector。

unordered_map大法好~

leetcode解题报告(19):Contains Duplicate II的更多相关文章

  1. LeetCode解题报告—— Word Search & Subsets II & Decode Ways

    1. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be con ...

  2. LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal

    1. Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no ...

  3. LeetCode解题报告—— Reverse Linked List II & Restore IP Addresses & Unique Binary Search Trees II

    1. Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-pass ...

  4. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  5. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  6. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  7. LeetCode解题报告汇总! All in One!

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 把自己刷过的所有题目做一个整理,并且用简洁的语言概括了一下思路,汇总成了一个表格. 题目 ...

  8. LeetCode解题报告—— Combination Sum & Combination Sum II & Multiply Strings

    1. Combination Sum Given a set of candidate numbers (C) (without duplicates) and a target number (T) ...

  9. LeetCode解题报告—— Permutations & Permutations II & Rotate Image

    1. Permutations Given a collection of distinct numbers, return all possible permutations. For exampl ...

随机推荐

  1. docker 实践十一:docker 跨主机通讯

    在上一篇了解了关于 docker 的网络模型后,本篇就基于上一篇的基础来实现 docker 的跨主机通信. 注:环境为 CentOS7,docker 19.03. 本篇会尝试使用几种不同的方式来实现跨 ...

  2. 邮件标准协议:MIME(Multipurpose Internet Mail Extensions)

    MIME(多用途互联网邮件扩展)指的是一系列电子邮件技术规范 ,主要包括 RFC 2045~2049   传统的电子邮件只能使用 ASCII 字符,导致非英文字符都不能在电子邮件中使用 而且电子邮件中 ...

  3. 谷歌chrome浏览器提示“喔唷 崩溃啦”的解决方案

    原因分析:有可能是注册列表被一些卫士类优化工具或杀毒软件优化了. 解决方案:1. 卸载谷歌浏览器. ①开始→控制面板→添加或删除程序→找到谷歌浏览器卸载(卸载时勾选删除数据) ② 进入注册列表删除谷歌 ...

  4. 软键盘 显示隐藏 测量高度 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  5. hdu 1501 贪心问题

    这道题目的关键就是逐个搜索的过程 找个时间得复习一下dfs了    这里使用temp作为参照变量 每次比较以后(由于已经排序好) 已temp为参照进行下一次的比较

  6. AngularJS在IE下页面缓存问题

    问题: 在使用AngularJS发出请求(GET)获取服务端数据,然后再绑定到页面中,你会发现在IE中总是显示原来的数据结果.这时候我们就会知道,IE做了缓存. 解决办法: 我们可以在AngularJ ...

  7. C# 字符串按设置的格试在前面或后面增加空格或其它字符

    public string lengadd(string stringa, string stringb, int count, int mode) //以stringa的长度,未到count的长度则 ...

  8. 解读生命密码的基本手段 ——DNA测序技术的前世今生

    解读生命密码的基本手段 ——DNA测序技术的前世今生 任鲁风  于军 (中国科学院基因组科学及信息重点实验室,北京基因组研究所) DNA(脱氧核糖核酸)和RNA(核糖核酸)是生命体的两种最基本组成物质 ...

  9. javascript动态添加html节点

    之前一直没怎么接触需要动态添加和删除html节点的项目,这次项目中用到了,也学习了. 在一个<table id="tab">标签中添加一个<tr id=" ...

  10. Ubuntu armhf 版本国内源

    Ubuntu armhf 版本国内源: deb http://mirrors.ustc.edu.cn/ubuntu-ports/ xenial main multiverse restricted u ...