carloscn / structstudy

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

leetcode2154: Keep Multiplying Found Values by Two #348

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.

You then do the following steps:

If original is found in nums, multiply it by two (i.e., set original = 2 * original). Otherwise, stop the process. Repeat this process with the new number as long as you keep finding the number. Return the final value of original.

Example 1:

Input: nums = [5,3,6,1,12], original = 3 Output: 24 Explanation:

Example 2:

Input: nums = [2,7,9], original = 4 Output: 4 Explanation:

Constraints:

1 <= nums.length <= 1000 1 <= nums[i], original <= 1000

carloscn commented 1 year ago

Analysis

int32_t find_final_value(int32_t* nums, size_t nums_size, int32_t original, int32_t *out)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_PTR(out);
    UTILS_CHECK_LEN(nums_size);

    for (size_t i = 0; i < nums_size; i ++) {
        for (size_t j = 0; j < nums_size - i - 1; j ++) {
            if (nums[j] > nums[j + 1]) {
                utils_swap_int32(nums + j, nums + j + 1);
            }
        }
    }

    bool flag = false;
    size_t i = 0;
    while (i < nums_size) {
        if (nums[i] == original) {
            original *= 2;
            flag = true;
        }
        i ++;
    }

    *out = flag == true ? original * 2 : original;

    LOG("the output is %d\n", *out);

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169095 https://github.com/carloscn/structstudy/commit/980c682648b68735457dcff6f5b20a9b67c989a4