码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Contains Duplicate II

时间:2015-06-02 09:22:08      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:duplicate   hash   

LeetCode Contains Duplicate II

题目

技术分享

思路

Contains Duplicate一模一样,加个坐标判断即可。

代码

bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
    if (numsSize <= 1) return false;
    int length = 100007;
    if (numsSize < length) length = numsSize;
    int * hash = (int*)malloc(sizeof(int) * length);
    int * pos = (int*)malloc(sizeof(int) * length);
    bool * used = (bool*)malloc(sizeof(bool) * length);
    for (int i = 0; i < length; i++) used[i] = false;
    for (int i = 0; i < numsSize; i++) {
        int p = (nums[i] + numsSize) % numsSize;
        while (used[p]) {
            if (hash[p] == nums[i] && i - pos[p] <= k) {
                free(hash);
                free(pos);
                free(used);
                return true;
            }
            p++;
            if (p == length) p = 0;
        }
        hash[p] = nums[i];
        pos[p] = i;
        used[p] = true;
    }
    free(hash);
    free(pos);
    free(used);
    return false;
}

LeetCode Contains Duplicate II

标签:duplicate   hash   

原文地址:http://blog.csdn.net/u012925008/article/details/46323181

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!