Contains Duplicate II
2016-07-23 14:05
316 查看
https://leetcode.com/problems/contains-duplicate-ii/
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.
这道题目源自 [Contains Duplicate] (http://blog.csdn.net/hemmingway/article/details/52003577)
不同的是查找到的两个相同元素的下标距离不能超过给定的参数K。所以可以把上个题目改进一下,创建一个index数组,将nums数组元素排序前后的index关系映射存储起来,比如有个元素3的原先的下标是 i,排序过后的下表到了数组的位置j, 则有 index[j]=i;
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.
这道题目源自 [Contains Duplicate] (http://blog.csdn.net/hemmingway/article/details/52003577)
不同的是查找到的两个相同元素的下标距离不能超过给定的参数K。所以可以把上个题目改进一下,创建一个index数组,将nums数组元素排序前后的index关系映射存储起来,比如有个元素3的原先的下标是 i,排序过后的下表到了数组的位置j, 则有 index[j]=i;
bool containsNearbyDuplicate(int* nums, int numsSize, int k) { int i, j, key; int *index = (int *)malloc(numsSize * sizeof(int)); // store index //memset(index, 0, numsSize * sizeof(int)); for(i = 1; i < numsSize; ++i) { j = i - 1; key = nums[i]; while(j > 0 && nums[j] > key) { nums[j + 1] = nums[j]; // move to back index[j + 1] = index[j]; j--; } //if(j != (i-1)) //{ nums[j + 1] = key; index[j + 1] = i; // map new index to old //} /* check */ if((nums[j] == key) && (i - index[j] <= k)) return true; } free(index); return false; }
相关文章推荐
- 调用http://apistore.baidu.com网站的接口
- HDU5728 2016 Multi-University Training Contest 1 (递归+欧拉函数)
- http://blog.csdn.net/mindfloating/article/details/51534289
- UVA 11076-Add Again
- soft raid5阅读笔记之十四--resync和recovery的区别
- soft raid5阅读笔记之十三--异或操作
- soft raid5阅读笔记之十二--DMA相关
- 5. Longest Palindromic Substring && 214. Shortest Palindrome && 336. Palindrome Pairs
- soft raid5阅读笔记之十--状态标志
- soft raid5阅读笔记之九--MD中的superblock
- 373. Find K Pairs with Smallest Sums && 378. Kth Smallest Element in a Sorted Matrix
- soft raid5阅读笔记之七--MD中的bitmap
- maven install时报错Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile
- Contains Duplicate
- POJ:1995 Raising Modulo Numbers(快速幂)
- 2016 Multi-University Training Contest 2 1006 Fantasia (hdu5739) 【割点 无向图dfs树 树形dp】
- 2016 Multi-university-training-contests-2 1006 点双连通分量
- 在QMainWindow添加控件,无法显示问题
- error: Setup script exited with error: command 'gcc' failed with exit status 1
- E - Doing Homework again hd 1789