219. Contains Duplicate II
来源:互联网 发布:jenkins 远程windows 编辑:程序博客网 时间:2024/06/03 17:04
Given an array of integers and an integer k, find out whether there are two distinct indicesi andj in the array such that nums[i] = nums[j] and theabsolute difference betweeni and j is at mostk.
Approach #1
public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_set<int> s; int n=nums.size(); if(k<=0)return false;//不存在这样的情况 for(int i=0;i<n;i++) { if(i>k) s.erase(nums[i-k-1]);//前面的数据已经超出了范围,即使找到相同的数也不符合条件<=k if(s.find(nums[i])!=s.end())return true;//找到重复值,因为范围外的数据已经被删除,所以不比判断下标 else s.insert(nums[i]); } return false; }注意k<0,无解,k=0时,不符合题意distinct indices i and j
也可以用map存放数据,把下标存进去,判断下标
阅读全文
0 0
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 栈的压入、弹出序列
- 设计模式3-单例模式
- 安装php-5.6.31
- opencv滑动条的创建与使用
- FAST特征点检测
- 219. Contains Duplicate II
- Hibernate实体映射笔记
- Linux下的文件目录及其作用
- go服务器向页面推送消息
- Ext 整合富文本编辑器Tinymce插件
- Linux基础知识:网络属性配置
- java中的 集合框架
- Openfiler之二:iSCSI应用
- opencv训练xml文件方法步骤