LeetCode刷题笔录First Missing Positive
2014-08-06 02:15
441 查看
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
and
Your algorithm should run in O(n) time and uses constant space.
这题的基本解法是用数组元素本身作为下标,把i+1放到A[i]里面去(当然要交换数组元素,不能把A[i]的元素丢掉)。如果是超出数组下标允许范围的元素(<0或>=A.length)就不管它,放在原处。这样子[3,4,-1,1]经过一次循环后会变成[1,-1,3,4]。然后再一遍循环,看A[i]==i+1.不是的话那么就返回i+1.
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.
这题的基本解法是用数组元素本身作为下标,把i+1放到A[i]里面去(当然要交换数组元素,不能把A[i]的元素丢掉)。如果是超出数组下标允许范围的元素(<0或>=A.length)就不管它,放在原处。这样子[3,4,-1,1]经过一次循环后会变成[1,-1,3,4]。然后再一遍循环,看A[i]==i+1.不是的话那么就返回i+1.
public class Solution { public int firstMissingPositive(int[] A) { int index = 0; while(index < A.length){ if(A[index] >= 1 && A[index] <= A.length && A[index] != index + 1 && A[A[index] - 1] != A[index]){ swap(A, index, A[index] - 1); } else{ index++; } } for(int i = 0; i < A.length; i++){ if(A[i] != i + 1){ return i + 1; } } return A.length + 1; } public void swap(int[] A, int i, int j){ int temp = A[i]; A[i] = A[j]; A[j] = temp; } }
相关文章推荐
- [LeetCode P41] First Missing Positive
- [LeetCode]First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- leetcode || 41、First Missing Positive 问题
- LeetCode First Missing Positive
- [LeetCode]41 First Missing Positive
- Leetcode NO.41 First Missing Positive
- [leetcode 41] First Missing Positive
- LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****
- [leetcode] First Missing Positive
- First Missing Positive--LeetCode
- LeetCode 41 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