Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
public class Solution {
public void sortColors(int[] A) {
int start = 0;
int end = A.length-1;
for(int i=0;i<A.length;i++) {
if(A[i]==0 && i>start) {
int tmp = A[start];
A[start] = A[i];
A[i] = tmp;
start++;
i--;
} else if(A[i]==2 && i<end) {
int tmp = A[end];
A[end] = A[i];
A[i] = tmp;
end--;
i--;
}
}
}
}
public class Solution {
public void sortColors(int[] nums) {
int s = 0;
int e = nums.length - 1;
int cur = 0;
while (cur <= e) {
int val = nums[cur];
if (val == 0) {
nums[cur] = nums[s];
nums[s] = 0;
s++;
cur = Math.max(cur, s);
} else if (val == 2) {
nums[cur] = nums[e];
nums[e] = 2;
e--;
} else {
cur++;
}
}
}
}
=======
public class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
int start = 0;
int end = nums.length - 1;
for (int i = 0; i <= end; i++) {
if (nums[i] == 0) {
nums[i] = nums[start];
nums[start] = 0;
start++;
} else if (nums[i] == 2) {
nums[i] = nums[end];
nums[end] = 2;
end--;
i--;
}
}
}
}
======
public class Solution {
public void sortColors(int[] nums) {
int end = nums.length - 1;
int start = 0;
for (int i = 0; i <= end; i++) {
if (nums[i] == 0) {
nums[i] = 1;
nums[start++] = 0;
} else if (nums[i] == 2) {
while (end > i && nums[end] == 2) end--;
nums[i] = nums[end];
nums[end] = 2;
i--;
end--;
}
}
}
}
public class Solution {
public void sortColors(int[] nums) {
int s = 0;
int e = nums.length - 1;
int cur = 0;
while (cur <= e) {
int val = nums[cur];
if (val == 0) {
nums[cur] = nums[s];
nums[s] = 0;
s++;
cur = Math.max(cur, s);
} else if (val == 2) {
nums[cur] = nums[e];
nums[e] = 2;
e--;
} else {
cur++;
}
}
}
}
=======
public class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
int start = 0;
int end = nums.length - 1;
for (int i = 0; i <= end; i++) {
if (nums[i] == 0) {
nums[i] = nums[start];
nums[start] = 0;
start++;
} else if (nums[i] == 2) {
nums[i] = nums[end];
nums[end] = 2;
end--;
i--;
}
}
}
}
======
public class Solution {
public void sortColors(int[] nums) {
int end = nums.length - 1;
int start = 0;
for (int i = 0; i <= end; i++) {
if (nums[i] == 0) {
nums[i] = 1;
nums[start++] = 0;
} else if (nums[i] == 2) {
while (end > i && nums[end] == 2) end--;
nums[i] = nums[end];
nums[end] = 2;
i--;
end--;
}
}
}
}
没有评论:
发表评论