carloscn / structstudy

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

leetcode645:错误的集合(set-mismatch) #117

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。

给定一个数组 nums 代表了集合 S 发生错误后的结果。

请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

示例 1: 输入:nums = [1,2,2,4] 输出:[2,3]

示例 2: 输入:nums = [1,1] 输出:[1,2]  

提示: 2 <= nums.length <= 104 1 <= nums[i] <= 104

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/set-mismatch

carloscn commented 1 year ago

问题分析

static int32_t mis_set(int64_t *array, size_t *len)
{
    int32_t ret = 0;
    size_t i = 0;
    size_t count = 0;

    UTILS_CHECK_PTR(array);
    UTILS_CHECK_PTR(len);
    UTILS_CHECK_LEN(*len);

    for (i = 0; i < *len; i ++) {
        if (array[i] != (i + 1)) {
            array[count++] = array[i];
            array[count++] = i + 1;
        }
    }

    *len = count;

finish:
    return ret;
}
fn mis_set(array : &mut [i64], len : &mut usize) -> i32
{
    let mut ret:i32 = 0;
    let mut i:usize = 0;
    let mut count:usize = 0;
    let mut sz = *len;

    if sz == 0 {
        return ret;
    }

    while i < sz {
        if array[i] != (i + 1) as i64 {
            array[count] = array[i];
            count += 1;
            array[count] = (i + 1) as i64;
            count += 1;
        }
        i += 1;
    }
    *len = count;

    return ret;
}
carloscn commented 1 year ago

code

https://github.com/carloscn/structstudy/blob/master/c_programming/array/40_set-mismatch_645.c https://github.com/carloscn/structstudy/blob/master/rust_programming/array/src/n40_set_mismatch_645.rs

result

image