219. Contains Duplicate II---数组中两个重复的数字的下标最多相差k
来源:互联网 发布:网络流行字体手写体 编辑:程序博客网 时间:2024/06/05 05:43
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.
方法一、hash
bool containsNearbyDuplicate(vector<int>& nums, int k){ int len = nums.size(); if(len<0) { return false; } map<int,int> mp; for(int i=0; i<len; i++) { if(mp.find(nums[i]) != mp.end()) { if((i-mp[nums[i]])<=k) { return true; break; } else { mp[nums[i]] = i; } } else { mp.insert(pair<int,int>(nums[i],i)); } } return false;}
方法二、集合的方法
bool containsNearbyDuplicate(vector<int>& nums, int k) { set<int> cand; for (int i = 0; i < nums.size(); i++) {//首先将前面的k+1个数字先插入进集合中,集合的性质是里面的所有数字都不会重复 if (i > k) cand.erase(nums[i-k-1]); /*insert(key_value); 将key_value插入到set中 ,返回值是pair<set<int>::iterator,bool>,bool标志着插入是否成功,而iterator代表插入的位置,若key_value已经在set中,则iterator表示的key_value在set中的位置。inset(first,second);将定位器first到second之间的元素插入到set中,返回值是void.*/ if (!cand.insert(nums[i]).second) return true; } return false; }
0 0
- 219. Contains Duplicate II---数组中两个重复的数字的下标最多相差k
- 219. Contains Duplicate II (判断数组中是否有重复元素且其下标之差不超过k)
- Contains Duplicate II 找出数组中是否有重复元素,长度小于k
- leetcode 217 Contains Duplicate 数组中是否有重复的数字
- 数组中重复次数最多的数字
- LeetCode:计算相同数组元素的下标差(Contains Duplicate II)
- [Java]Contains Duplicate II 包含重复数字
- Contains Duplicate II:计算数组内位置之差不超过K的两元素位置
- (LeetCode)Contains Duplicate II --- 查找重复的元素升级版
- 排序数组中重复最多的数字长度
- 查找数组中重复次数最多的数字
- Contains Duplicate [leetcode] 判断数组中是否有重复的元素
- leetcode解题之219 # Contains Duplicate II Java版 (数组中出现重复元素)
- 一个数组中两个数的和为N,找出这两个数字的下标
- Leetcode: 217. Contains Duplicate(数组是否包含重复数字)
- 数组中两个数之和等于某个数字,返回这两个数的下标
- Leetcode:219. Contains Duplicate II(数组是否含有重复元素)
- 219. Contains Duplicate II
- java调用dll动态库文件的一般总结
- 使用 C++ 创建你的第一个 Metro 风格应用
- 319. Bulb Switcher
- Android UI美化之 shape的使用及其属性总结
- centos安装rabbitmq
- 219. Contains Duplicate II---数组中两个重复的数字的下标最多相差k
- cocos2d-js 安装方式
- maven命名规则(转)
- Linux桌面系统各种字体配置
- 偏移向量并查集——A Bug's Life
- 带默认参数的函数
- 针对数据库中含大字段类型字段的表,进行数据迁移
- 项目应用:HTTP 状态码
- 约瑟夫环问题