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.
Idea: Another way of thinking this problem is to move all the 0’s to the front of the array and move all the 2’s to the end of the array. So we use scan the array from left to right and use two pointers to remember the positions to move 0’s and 2’s to. Once we find a 0, move it to p0, p0++; once we find a 2, move it to p2, p2--; if it is 1, just go forward.
Since both p0 and the scanner, e.g. i, start from 0, they need to skip the 0’s in the front together. So when A[i]==0, both p0 and i increase 1.
Since the end of the original array may be 2, so the swap may swap two 2’s. Therefore i can not go forward in handling 2’s.
Time: O(n) Space: O(1)
Code:
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_4ttYwMl_uJzWpFN_i6Br26Ka-UAuQurT862HR7CPovBTgDYQCBanMOLWbaQOGbH0WYA43qWxXoN4PqliLI_FkbKJCx7qwClhykGbIBdArsNfC-u2A40ptxiu2kvmgHmI8MShLaH4fbtl/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> public class Solution {
public void sortColors(int[] A) {
int p0=0;
int p2=A.length-1;
int i=0;
while(i<=p2)
{
switch(A[i])
{
case 0:
swap(A,i,p0);
p0++;
i++;
break;
case 1:
i++;
break;
case 2:
swap(A,i,p2);
p2--;
break;
}
}
}
public void swap(int[] A, int i, int j)
{
int tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}
}
</code></pre>
No comments:
Post a Comment