Trump看见小红帽的川粉就会嘲笑 (转载)# EB23 - 劳工卡
f*e
1 楼
*************************
int temp = A[i];
A[i] = A[A[i] -1];
A[A[i] - 1] = temp;
******************************
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp; ---------这几行过了, leetcode test.
*******************************
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.
My solution:
public class Solution {
public int firstMissingPositive(int[] A) {
int i = 0;
while(i < A.length){
if(A[i] > 0 && A[i] <= A.length && A[i] != i + 1 && A[i] != A[A[
i] - 1]){
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp;
} else{
++i;
}
}
int j = 0;
while(j < A.length && A[j] - 1 == j) ++j;
return j+1;
}
}
百思不得其解, 请高人指点.
int temp = A[i];
A[i] = A[A[i] -1];
A[A[i] - 1] = temp;
******************************
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp; ---------这几行过了, leetcode test.
*******************************
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.
My solution:
public class Solution {
public int firstMissingPositive(int[] A) {
int i = 0;
while(i < A.length){
if(A[i] > 0 && A[i] <= A.length && A[i] != i + 1 && A[i] != A[A[
i] - 1]){
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp;
} else{
++i;
}
}
int j = 0;
while(j < A.length && A[j] - 1 == j) ++j;
return j+1;
}
}
百思不得其解, 请高人指点.