carloscn / structstudy

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

leetcode674:最长连续递增序列(longest-continuous-increasing-subsequence) #119

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。

连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。

示例 1: 输入:nums = [1,3,5,4,7] 输出:3 解释:最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。

示例 2: 输入:nums = [2,2,2,2,2] 输出:1 解释:最长连续递增序列是 [2], 长度为1。   提示: 1 <= nums.length <= 104 -109 <= nums[i] <= 109

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/longest-continuous-increasing-subsequence

carloscn commented 1 year ago

问题分析

C版本

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

    UTILS_CHECK_PTR(array);
    UTILS_CHECK_PTR(len);

    for (i = 1; i < *len; i ++) {
        if (array[i] > array[i - 1]) {
            count ++;
            max_count = (count > max_count) ? count : max_count;
        } else {
            count = 0;
        }
    }

    *len = max_count + 1;

finish:
    return ret;
}

RUST版本

fn longest_continuous_seq(array:&[i64], len:&mut usize) -> Result<i32, &'static str>
{
    let mut i = 1;
    let mut count = 0;
    let mut max_count = 0;

    if 0 == *len {
        return Err("input error");
    }

    while i < *len {
        if array[i] > array[i - 1] {
            count += 1;
            if count > max_count {
                max_count = count;
            }
        } else {
            count = 0;
        }
        i += 1;
    }

    *len = max_count + 1;

    return Ok(0);
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/array/41_longest-continuous-increasing-subsequence_674.c https://github.com/carloscn/structstudy/blob/master/rust_programming/array/src/n41_longest_continuous_increasing_subsequence_674.rs

result:

image