描述

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. Python学习路线2019升级版(课程大纲+视频教程+网盘资源下载)

    2019最新Python全栈+人工智能学习路线升级版 全面涵盖前端.后端.爬虫.数据挖掘.人工智能等课程(课程大纲+视频教程+网盘资源下载)! 学习路线四大亮点: 1.人工智能三大主流框架全覆盖 2. ...

  2. SSH安全加固

    SSH安全加固 配置文件: /etc/ssh/sshd_config # This file is automatically generated at startup KexAlgorithms c ...

  3. Linux下如何挂载文件,并设置开机自动挂载

    首先保证服务端安装了 查看是否安装命令: nfsstat yum install nfs-utils 安装nfs-utils 192.168.50.85(服务端)192.168.50.83(客户端) ...

  4. Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制)

    使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...

  5. laravel 中将一对多关联查询的结果去重处理

    先交代下数据表结构 主表(订单表)order数据 ord_id order_sn 1 EX2019100123458 其中主键为order_id(订单id) 子表(门票表)order_item数据 o ...

  6. git push error. ! [rejected] master -> master (non-fast-forward)

    错误提示: Cheetah@xxxx MINGW64 /e/Projs/enft/data/cv_key_frame (master) $ git push To github.com:Anthony ...

  7. iOS - error:unrecognized selector sent to class 导入第三方SDK .a后不识别,运行崩溃

    今天将app统计的.a静态库包含到一个app应用中,调试时报下面的错误: *** Terminating app due to uncaught exception 'NSInvalidArgumen ...

  8. 使用Django时需要注意的八个要点

    1.在settings.py中使用os. path.dirname() 常用代码如下: # settings.py import os PROJECT_DIR = os.path.dirname(__ ...

  9. nginx 反向代理配置(一)

    文章参考:https://blog.csdn.net/physicsdandan/article/details/45667357       什么是代理?       代理在普通生活中的意义就是本来 ...

  10. TensorFlow实现Softmax Regression识别手写数字

    本章已机器学习领域的Hello World任务----MNIST手写识别做为TensorFlow的开始.MNIST是一个非常简单的机器视觉数据集,是由几万张28像素*28像素的手写数字组成,这些图片只 ...