设为首页 加入收藏

TOP

[LeetCode]First Missing Positive
2015-07-20 17:38:18 来源: 作者: 【 】 浏览:3
Tags:LeetCode First Missing Positive

Given an unsorted integer array, find the first missing positive integer.

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

public class Solution {
	public int firstMissingPositive(int[] A) {
		if (A.length == 0)
			return 1;
		bucketSort(A);
		for (int i = 0; i < A.length; i++) {
			if (A[i] - 1 != i)
				return i + 1;
		}
		return A.length + 1;
	}

	private void bucketSort(int[] A) {
		for (int i = 0; i < A.length; i++) {
			while (A[i] != i + 1) {
				if (A[i] > A.length || A[i] < 1 || A[i] == A[A[i] - 1])
					break;
				int temp =A[A[i]-1];
				A[A[i] - 1] = A[i];
				A[i] = temp;
			}
		}
	}
}





】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C/C++函数指针参数不匹配问题 下一篇hdu 5037 Frog(贪心)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·「链表」是一种怎样 (2025-12-25 19:20:51)
·C 语言中的链表有哪 (2025-12-25 19:20:48)
·c语言中的链表怎么学 (2025-12-25 19:20:45)
·Redis 分布式锁全解 (2025-12-25 17:19:51)
·SpringBoot 整合 Red (2025-12-25 17:19:48)