Skip to content

[LeetCode] 219. 存在重复元素 II #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Aug 5, 2019 · 0 comments
Open

[LeetCode] 219. 存在重复元素 II #25

Animenzzzz opened this issue Aug 5, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

解题思路:使用哈希表,一次遍历就够了。需要注意的地方:如果遇到比k小的间距,直接return true就好,如果遇到比k还大的间距,需要更新好k_index的值,防止之后还会遇到此重复的值且小于k间距。

C解题:

struct HashMap {
    int number;
    int k_index;
    UT_hash_handle hh;
};
bool containsNearbyDuplicate(int* nums, int numsSize, int k){
    struct HashMap *hashmap = NULL,*hashtmp = NULL;
    for (int i = 0; i < numsSize; i++)
    {
        HASH_FIND_INT(hashmap,&nums[i],hashtmp);
        if (hashtmp){
            if(i-hashtmp->k_index <= k){
                return true;
            }else{
                hashtmp->k_index = i;
            }
        }
        else{
            struct HashMap *tmp = (struct HashMap*)malloc(sizeof(struct HashMap));
            tmp->number = nums[i];
            tmp->k_index = i;
            HASH_ADD_INT(hashmap,number,tmp);
        }
    }
    return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant