LeetCode First Missing Positive
来源:互联网 发布:java怎么包装简历 编辑:程序博客网 时间:2024/06/05 10:56
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.
思路分析:这题题目意思说的不是很清楚,详细解释应该是如果你把给定的数组排序,从前向后数正整数1,2,3 ...等等,找到第一个缺失的正整数。解题思路是做交换,目标是要尽量把A[i]放在A[A[i]-1]处(可以设想一个perfect的正整数数组应该是 1 2 3... index为0 1 2...)实质是桶排序,每次当A[i] - 1!= i的时候,将A[i]与A[A[i] - 1]交换,直到无法交换位置。然后从头开始扫一遍找到第一个缺失的正整数即可。
详细图解可以参考
http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html
http://leetcodenotes.wordpress.com/2013/07/17/first-missing-positive/
AC Code
public class Solution { public int firstMissingPositive(int[] A) { int l = A.length; int i = 0; while(i < l){ if(A[i] != i+1 && A[i] > 0 && A[i] <= l && A[i] != A[A[i] - 1]){ swap(A, i, A[i] - 1); } else i++; } for(int ii = 0; ii < l; ii++){ if(A[ii] != ii+1) return ii+1; } return l + 1; } public 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 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
- 唐巧-猿题库客户端的技术细节
- 网络请求数据
- BZOJ 3574 HNOI 2014 抄卡组 字符串Hash+STL
- 如何探索BI Content? 如何查找DataSource和table的mapping?
- javascript比较两个日期的先后
- LeetCode First Missing Positive
- 算法整理:查找算法简单整理
- CMMI 和敏捷经典概括
- 很有趣的一道编程题,子弹分发问题
- Leetcode Pascal's Triangle
- Cocos2d-x分享一个封装的Sqlite3的DBUtil类
- Android设置虚线、圆角、渐变
- webdriver里的PageFactory.InitElements()
- Ping 1000个包看丢跑率