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

LeetCode Contains Duplicate II

2015-06-02 08:08 387 查看

LeetCode Contains Duplicate II

题目



思路

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

代码

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