f**********e 发帖数: 288 | 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;
}
}
百思不得其解, 请高人指点. | l*********8 发帖数: 4642 | 2 int temp = A[i];
A[i] = A[A[i] -1];
A[A[i] - 1] = temp; // A[i] 已经不是原来的A[i]了, 改成A[temp-1] = temp;
【在 f**********e 的大作中提到】 : ************************* : 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.
| f**********e 发帖数: 288 | 3 不是用, temp存下来了吗?
【在 l*********8 的大作中提到】 : int temp = A[i]; : A[i] = A[A[i] -1]; : A[A[i] - 1] = temp; // A[i] 已经不是原来的A[i]了, 改成A[temp-1] = temp;
| l*********8 发帖数: 4642 | 4 A[A[i] - 1] 里的A[i]不是原来的A[i]了
【在 f**********e 的大作中提到】 : 不是用, temp存下来了吗?
| d********3 发帖数: 25 | | f**********e 发帖数: 288 | | l****r 发帖数: 118 | 7 我也刚做了这题。:)
【在 f**********e 的大作中提到】 : 囧.... : 多谢两位.:-)
|
|