Leetcode First Missing Positive
2016-07-19 05:08
435 查看
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.
Difficulty: Hard
public class Solution {
public void swap(int[] nums, int index1, int index2){
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
public int firstMissingPositive(int[] nums) {
int count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] <= 0){
swap(nums, count, i);
count++;
}
}
for(int i = count; i < nums.length; i++){
if(nums[i] <= nums.length - count){
if(nums[i] != nums[nums[i] - 1 + count]){
swap(nums, i, nums[i] - 1 + count);
i--;
}
else{
swap(nums, i, nums[i] - 1 + count);
}
}
}
for(int i = count; i < nums.length; i++){
if(nums[i] != i - count + 1)
return (i - count + 1);
}
return nums.length - count + 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.
Difficulty: Hard
public class Solution {
public void swap(int[] nums, int index1, int index2){
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
public int firstMissingPositive(int[] nums) {
int count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] <= 0){
swap(nums, count, i);
count++;
}
}
for(int i = count; i < nums.length; i++){
if(nums[i] <= nums.length - count){
if(nums[i] != nums[nums[i] - 1 + count]){
swap(nums, i, nums[i] - 1 + count);
i--;
}
else{
swap(nums, i, nums[i] - 1 + count);
}
}
}
for(int i = count; i < nums.length; i++){
if(nums[i] != i - count + 1)
return (i - count + 1);
}
return nums.length - count + 1;
}
}
相关文章推荐
- Leetcode Excel Sheet Column Title
- Leetcode Palindrome Linked List
- Leetcode Compare Version Numbers
- Leetcode Insertion Sort List
- Leetcode Unique Binary Search Trees
- Leetcode Linked List Cycle II
- Leetcode Remove Nth Node From End of List
- Leetcode Integer to Roman
- Leetcode Valid Anagram
- Leetcode Single Number II
- 大公司还是小公司(非常全面和有道理,居然还是原创)
- Leetcode Pascal's Triangle
- Leetcode Balanced Binary Tree
- Leetcode Divide Two Integers
- Leetcode Sqrt(x)
- Leetcode Number of Digit One
- Leetcode Largest Number
- Leetcode Word Break II
- [leetcode] 118. Pascal's Triangle
- php判断是否为今天