Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 886184a

Browse files
author
Zhang Xiaodong
committed
solve 41
1 parent 7295559 commit 886184a

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ mod s0037_sudoku_solver;
3636
mod s0038_count_and_say;
3737
mod s0039_combination_sum;
3838
mod s0040_combination_sum_ii;
39+
mod s0041_first_missing_positive;
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* [41] 缺失的第一个正数
3+
*
4+
* 给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
5+
* 请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
6+
*  
7+
* 示例 1:
8+
*
9+
* 输入:nums = [1,2,0]
10+
* 输出:3
11+
*
12+
* 示例 2:
13+
*
14+
* 输入:nums = [3,4,-1,1]
15+
* 输出:2
16+
*
17+
* 示例 3:
18+
*
19+
* 输入:nums = [7,8,9,11,12]
20+
* 输出:1
21+
*
22+
*  
23+
* 提示:
24+
*
25+
* 1 <= nums.length <= 5 * 10^5
26+
* -2^31 <= nums[i] <= 2^31 - 1
27+
*
28+
*/
29+
pub struct Solution {}
30+
31+
// problem: https://leetcode.cn/problems/first-missing-positive/
32+
// discuss: https://leetcode.cn/problems/first-missing-positive/discuss/?currentPage=1&orderBy=most_votes&query=
33+
34+
// submission codes start here
35+
36+
impl Solution {
37+
pub fn first_missing_positive(nums: Vec<i32>) -> i32 {
38+
let mut nums: Vec<i32> = nums;
39+
for i in 0..nums.len() {
40+
if nums[i] <= 0 || nums[i] >= nums.len() as i32 {
41+
continue;
42+
}
43+
if (i+1) as i32 != nums[i] {
44+
let j = (nums[i] - 1) as usize;
45+
nums.swap(i, j);
46+
}
47+
}
48+
for i in 0..nums.len() {
49+
if (i+1) as i32 != nums[i] {
50+
return (i+1) as i32;
51+
}
52+
}
53+
nums.len() as i32
54+
}
55+
}
56+
57+
// submission codes end
58+
59+
#[cfg(test)]
60+
mod tests {
61+
use super::*;
62+
63+
#[test]
64+
fn test_41() {
65+
assert_eq!(
66+
Solution::first_missing_positive(vec![8,2,3,1,8,1,2,8]),4
67+
)
68+
}
69+
}

0 commit comments

Comments
 (0)