From 21cf6e05d60a08b437bee62ad64c9c32644874cd Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 7 Aug 2024 11:58:25 +0800 Subject: [PATCH] 20240807 Finished --- src/problem/mod.rs | 3 +- .../p300_longest_increasing_subsequence.rs | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/problem/p300_longest_increasing_subsequence.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index a0fb807..c83ed68 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -196,4 +196,5 @@ mod p50_powx_n; mod p149_max_points_on_a_line; mod p70_climbing_stairs; mod p198_house_robber; -mod p139_word_break; \ No newline at end of file +mod p139_word_break; +mod p300_longest_increasing_subsequence; \ No newline at end of file diff --git a/src/problem/p300_longest_increasing_subsequence.rs b/src/problem/p300_longest_increasing_subsequence.rs new file mode 100644 index 0000000..ffb2c84 --- /dev/null +++ b/src/problem/p300_longest_increasing_subsequence.rs @@ -0,0 +1,55 @@ +/** + * [300] Longest Increasing Subsequence + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn length_of_lis(nums: Vec) -> i32 { + let n = nums.len(); + if n == 0 { + return 0; + } + + let mut length = 1; + let mut dp = vec![0;n + 1]; + dp[length] = nums[0]; + + for i in 1..n { + if nums[i] > dp[length] { + length += 1; + dp[length] = nums[i]; + } else { + // 二分查找dp中小于nums[i]的位置 + let (mut left, mut right, mut pos) = (1, length, 0); + while left <= right { + let middle = (right - left) / 2 + left; + if dp[middle] < nums[i] { + pos = middle; + left = middle + 1; + } else { + right = middle - 1; + } + } + + dp[pos + 1] = nums[i]; + } + } + + length as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_300() { + + } +}