LeetCode(219) Contains Duplicate II
来源:互联网 发布:淘宝代绣十字绣可信吗 编辑:程序博客网 时间:2024/06/06 00:44
题目
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 difference between i and j is at most k.
分析
题目描述:给定一个整数序列,查找是否存在两个下标分别为
定义一个长度最大为k的滑动窗口,用一个unordered_set维护窗口内的数字判断是否出现重复,使用两个指针
AC代码
class Solution {public: bool containsNearbyDuplicate(vector<int>& nums, int k) { if (nums.empty()) return false; int sz = nums.size(); //使用容器unordered_set 其查找性能为常量 unordered_set<int> us; int start = 0, end = 0; for (int i = 0; i < sz; ++i) { if (us.count(nums[i]) == 0) { us.insert(nums[i]); ++end; } else{ return true; } if (end - start > k) { us.erase(nums[start]); ++start; } }//for return false; }};
GitHub测试程序源码
0 0
- [leetcode-219]Contains Duplicate II(C)
- [leetcode] 219 Contains Duplicate II(map)
- LeetCode(219) Contains Duplicate II
- leetcode 219: Contains Duplicate II
- LeetCode 219:Contains Duplicate II
- Contains Duplicate II - LeetCode 219
- Leetcode[219]-Contains Duplicate II
- LeetCode 219 Contains Duplicate II
- Leetcode 219 Contains Duplicate II
- 【Leetcode】Contains Duplicate II #219
- Leetcode 219 Contains Duplicate II
- leetcode 219:Contains Duplicate II
- LeetCode 219: Contains Duplicate II
- leetcode: (219) Contains Duplicate II
- leetcode 219: Contains Duplicate II
- [Leetcode]#219 Contains Duplicate II
- [LeetCode 219] Contains Duplicate II
- [leetcode 219] Contains Duplicate II
- MySQL存储过程与存储函数的区别
- SSH:Struts1框架(JSTL的配置和使用)
- System.Web Namespaces
- Remote Windows®-command executor for Linux
- 为什么Java中的String是不可变的?
- LeetCode(219) Contains Duplicate II
- android Application Project目录结构
- MYSQL 时间
- 折线图(五)根据实际情况值,绘制在折线图坐标轴对应位置上
- bash: useradd: command not found
- HDU 5236 Article [概率DP]
- App Framework $.ui.loadContent 参数解释
- ArcGIS教程:创建最小成本廊道
- 关于iOS去除数组中重复数据的几种方法