您的位置:首页 > 大数据 > 人工智能

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;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: