LeetCode刷题记录 First Missing Positive
来源:互联网 发布:linux配置多个ip地址 编辑:程序博客网 时间:2024/06/09 20:39
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.
找到第一个消失的正整数。而且复杂度是O(n)
思路:排序,然后就很简单了。
但是怎么在O(n)的复杂里面排序呢。
要结合题目的特点,A[i]需要等于A[A[i] - 1],只要有不相等的就交换。
比如A[i]等于5,而如果要连续的正整数,5必须出现在A[A[i] - 1]也就是A[5-1]上。
最后排序而成的A就像[1,2,3,4,5,6,8,-4,6]这样。
很容易找出第一个消失的正整数是7
代码如下
public class FirstMissingPositive { public static void main(String[] args) { int[] A = new int[]{}; System.out.println("firstMissingPositive: " + firstMissingPositive(A)); } public static int firstMissingPositive(int[] A) { for (int i = 0; i < A.length; ) { if (A[i] == i + 1 || A[i] <= 0 || A[i] > A.length) { i++; } else if (A[A[i] - 1] != A[i]) { swap(A, A[i] - 1, i); } else { i++; } } int i = 0; while ( i < A.length) { if (A[i] != i + 1) { return i + 1; } i++; } return i + 1; } private static void swap(int[] A, int i, int j){ int temp = A[i]; A[i] = A[j]; A[j] = temp; }}
阅读全文
0 0
- LeetCode刷题记录 First Missing Positive
- Leetcode刷题记——41. First Missing Positive(第一个丢失的正数)
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- LeetCode First Missing Positive
- [leetcode] first missing positive
- LeetCode: First Missing Positive
- [LeetCode]First Missing Positive
- LeetCode-First Missing Positive
- [leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- LeetCode - First Missing Positive
- LeetCode | First Missing Positive
- 保留小数点2位,四舍五入,java
- Sql server高级查询
- POJ11251---Jungle Roads(最小生成树)
- Android音频框架笔记
- HttpServletRequestWrapper 编码问题
- LeetCode刷题记录 First Missing Positive
- BASE64加密与解密
- 键盘事件keydown,keypress,keyup区别
- 递归函数
- 微店 Android 插件化实践
- 小Tip之int...
- Fiddler调式使用知多少(一)深入研究
- 浏览器控件JxBrowser V6.14大版本发布 | 注入CSS
- 谈谈C语言的字面字符串