6.6 First Missing Positive
来源:互联网 发布:苹果launchpad软件 编辑:程序博客网 时间:2024/05/20 03:43
Link: https://oj.leetcode.com/problems/first-missing-positive/
My first thought is to create a hashmap of <Integer, Boolean>. Then go through the array A, e.g. for array element 1, we update the value to true on key 1.
Then we traverse the hashmap to get the first false after key 0.
Second thought: we cannot do sorting, since no sorting algo is O(n). //This is wrong. Only comparison sorting algorithms are bound by O(nlogn).
Solution: The idea is similar to Counting Sort. Since we can only use constant space, we can only use the array itself. In the first loop, we save positive numbers into the array in ascending order, A[0] = 1, A[1] = 2, A[2] = 3, ... by swapping array elements. We skip negative numbers, 0, and positive numbers whose values are larger than the array length. For the second loop, we check the first element which does not have A[i] = i+1. (Ref: http://blog.csdn.net/linhuanmars/article/details/20884585)
Time: O(2n) = O(n), Space: O(1)
Note: We cannot use swap(a, b) method to swap A[A[i]-1] and A[i]. Why?
(Figure: http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html)
public class Solution { public int firstMissingPositive(int[] A) { //code after reading the answer int n = A.length; int i = 0; while(i < n){ if(A[i] > 0 && A[i] <= n && A[i] != (i+1) && A[A[i] - 1] != A[i]){ //swap(A[A[i]-1], A[i]); int tmp = A[A[i]-1]; A[A[i]-1] = A[i]; A[i] = tmp; } else i++; } for(i = 0; i < n; i++){ if(A[i] != i+1) return i+1; } return n+1; } //private void swap(int a, int b){ //int tmp = a; //a = b; //b = tmp; //}}
- 6.6 First Missing Positive
- 6.6—排序—First Missing Positive
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- leetcode12: First Missing Positive
- First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- LeetCode First Missing Positive
- [leetcode] first missing positive
- First Missing Positive
- LeetCode: First Missing Positive
- First Missing Positive
- First Missing Positive
- [LeetCode]First Missing Positive
- 最上面的扑克牌
- 过滤器Filter
- OC专有注释
- 输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2。
- 【iOS】网络操作与AFNetworking
- 6.6 First Missing Positive
- 一个台阶总共有n 级,如果一次可以跳1 级,也可以跳2 级,求总共有多少总跳法,并分析算法的时间复杂度。
- Cython红黑树版
- struts2 result type=stream
- 常用idea快捷键
- 字符串的左旋转操
- 关于SVN目录结构分布
- iOS系类教程之用instruments来检验你的app
- mysql 字符集问题