Skip to content

Commit fc4844a

Browse files
committed
array: 排列
Change-Id: Ia1b7452288ce3a868a771cdf6e1599c6feb7fbc1
1 parent 95c427a commit fc4844a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: go/leetcode/41.缺失的第一个正数.go

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* @lc app=leetcode.cn id=41 lang=golang
3+
*
4+
* [41] 缺失的第一个正数
5+
*
6+
* https://leetcode-cn.com/problems/first-missing-positive/description/
7+
*
8+
* algorithms
9+
* Hard (36.29%)
10+
* Likes: 269
11+
* Dislikes: 0
12+
* Total Accepted: 23.4K
13+
* Total Submissions: 64.1K
14+
* Testcase Example: '[1,2,0]'
15+
*
16+
* 给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
17+
*
18+
* 示例 1:
19+
*
20+
* 输入: [1,2,0]
21+
* 输出: 3
22+
*
23+
*
24+
* 示例 2:
25+
*
26+
* 输入: [3,4,-1,1]
27+
* 输出: 2
28+
*
29+
*
30+
* 示例 3:
31+
*
32+
* 输入: [7,8,9,11,12]
33+
* 输出: 1
34+
*
35+
*
36+
* 说明:
37+
*
38+
* 你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
39+
*
40+
*/
41+
42+
// 原地交换排序,两次遍历
43+
// 交换后的数组要符合[1,2,3,4... ]的规则,第一个不符合这样规则的位置,就是结果
44+
func firstMissingPositive(nums []int) int {
45+
for i := 0; i < len(nums); i++ {
46+
for nums[i] > 0 && nums[i] < len(nums) && nums[nums[i] - 1] != nums[i] {
47+
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
48+
}
49+
}
50+
for i := 0; i < len(nums); i++ {
51+
if nums[i] != i+1 {
52+
return i+1
53+
}
54+
}
55+
return len(nums)+1
56+
}
57+

0 commit comments

Comments
 (0)