详细见:leetcode.com/problems/first-missing-positive
Java所用的算法不够清晰,见C和Python的while循环
while的作用:将val的值放置到val-1的位置上
Java Solution: github
package leetcode;
public class P041_FirstMissingPositive {
public static void main(String[] args) {
// System.out.println(new Solution1().firstMissingPositive(new int[]{1,2,0}));
// System.out.println(new Solution1().firstMissingPositive(new int[]{3,4,-1,1}));
System.out.println(new Solution1().firstMissingPositive(new int[]{8, 5, 4, 3, 2, 1}));
}
/*
* 测试用例肯定特别多,HashMap完成不了
* 时间O(N) 空间O(1)
* 巨魔性
* 先假设没有重复数字
* AC了
* leetcode 却不告诉时间和排名
* 1 ms
* 18.19%
*/
static class Solution1 {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int l = 0, r = nums.length;
while (l < r) {
if (nums[l] == l + 1) {
l ++;
} else if (nums[l] <= 1 || nums[l] > r || nums[nums[l] - 1] == nums[l]) {
nums[l] = nums[-- r];
} else {
int temp = nums[nums[l] - 1];
nums[nums[l] - 1] = nums[l];
nums[l] = temp;
}
}
return l + 1;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/first-missing-positive/
firstMissingPositive: AC 3ms 38.60%
firstMissingPositive2: AC 6ms 5.26%
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int firstMissingPositive(int* n, int s) {
char* m = (char*) malloc(sizeof(char) * (s + 2));
int i = 0;
memset(m, '0', s + 2);
for (i = 0; i < s; i ++) {
if (n[i] >= 1 && n[i] <= s)
m[n[i]] = '1';
}
for (i = 1; i <= s; i ++) {
if (m[i] == '0') break;
}
free(m);
return i;
}
void swap(int* a,int *b) {
int t = *a;
*a = *b;
*b = t;
}
int firstMissingPositive2(int* n, int s) {
int i = 0;
for (i = 0; i < s; i ++) {
while (n[i] > 0 && n[i] <= s && n[n[i] - 1] != n[i])
swap(n + i, n + n[i] - 1);
}
for (i = 0; i < s; i ++) {
if (n[i] != i + 1)
return i + 1;
}
return s + 1;
}
int main() {
int n[] = {3,4,-1,1};
int s = 4;
printf("answer is %d\r\n", firstMissingPositive2(n , s));
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/first-missing-positive/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月6日
@details: Solution: 55ms 34.42%
'''
class Solution(object):
def swap(self, n, i, j):
t = n[i]
n[i] = n[j]
n[j] = t
def firstMissingPositive(self, n):
"""
:type n: List[int]
:rtype: int
"""
nn = 0 if n == None else len(n)
if nn == 0: return 1
for i in range(nn):
while n[i] > 0 and n[i] <= nn \
and n[i] != i+1 and n[n[i]-1]!=n[i]:
self.swap(n, n[i] - 1, i)
for i in range(nn):
if i+1 != n[i]:
return i+1
return nn+1
if __name__ == "__main__":
n = [1, 1]
print(Solution().firstMissingPositive(n))