carloscn / structstudy

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

leetcode2057: Smallest Index With Equal Value #331

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.

x mod y denotes the remainder when x is divided by y.

Example 1:

Input: nums = [0,1,2] Output: 0 Explanation: i=0: 0 mod 10 = 0 == nums[0]. i=1: 1 mod 10 = 1 == nums[1]. i=2: 2 mod 10 = 2 == nums[2]. All indices have i mod 10 == nums[i], so we return the smallest index 0.

Example 2:

Input: nums = [4,3,2,1] Output: 2 Explanation: i=0: 0 mod 10 = 0 != nums[0]. i=1: 1 mod 10 = 1 != nums[1]. i=2: 2 mod 10 = 2 == nums[2]. i=3: 3 mod 10 = 3 != nums[3]. 2 is the only index which has i mod 10 == nums[i].

Example 3:

Input: nums = [1,2,3,4,5,6,7,8,9,0] Output: -1 Explanation: No index satisfies i mod 10 == nums[i].

Constraints:

1 <= nums.length <= 100 0 <= nums[i] <= 9

carloscn commented 1 year ago

Description

int32_t smallest_equal(int32_t* nums, size_t len, int32_t *index)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_PTR(index);
    UTILS_CHECK_LEN(len);

    *index = -1;

    for (size_t i = 0; i < len; i ++) {
        if (i % 10 == nums[i]) {
            *index = (int32_t) i;
            goto finish;
        }
    }

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168600 https://github.com/carloscn/structstudy/commit/3a2125a93a9a6fe4f330b9d8400a0af5b0e15721