carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode219:存在重复元素 II(contains-duplicate-ii) #64

Open carloscn opened 2 years ago

carloscn commented 2 years ago

问题描述:

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

示例 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

提示: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/contains-duplicate-ii

carloscn commented 2 years ago

问题分析:

leetcode217:存在重复元素(contains-duplicate) 问题类似,只是判断条件换一下。

static int32_t contains_duplicate(int64_t *array, size_t sz, int64_t k, bool *result)
{
    int64_t i = 0, j = 0;;
    int32_t ret = 0;
    int64_t e = 0;

    UTILS_CHECK_LEN(sz);
    UTILS_CHECK_PTR(array);
    UTILS_CHECK_PTR(result);

    for (i = 0; i < sz; i ++) {
        e = array[i];
        for (j = i + 1; j < sz; j ++) {
            if ((e == array[j]) &&
                (utils_int64_abs(i - j)) <= k) {
                *result = true;
                goto finish;
            }
        }
    }

    *result = false;

finish:
    return ret;
}
carloscn commented 2 years ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/array/20_contains-duplicate-ii_219.c

result:

image