Leetcode::Sort colors

1.只需要遍历数组一遍;

使用start记录存储0的位置;使用end记录存储2的位置;

A[cur]等于1时往后移动cur;A[cur]等于其他则进行交换;

class Solution {
public:
inline void swap( int &a, int &b)
{
int tmp;
tmp=a;
a=b;
b=tmp;
}

void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( n <= 1 )
return;

int start,end,cur;
start=cur=0;
end=n-1;

while( cur <= end )
{
if( A[cur] == 0 )
{
if( start == cur )
{
start++;
cur++;
}
else if ( start < cur )
{
swap( A[start++], A[cur] );
}
}
else if( A[cur] == 2 )
{
if( cur == end )
{
return;
}
else
{
while( cur < end && A[end] == 2 )
{
end--;
}
if(cur==end)
return;

swap(A[end--],A[cur]);
}
}
else
{
cur++;
}
}

}
};

2.需要两个指针,一个头指针和一个尾指针;两次遍历数组,第一次把所有0放到前面,第二次交换1和2;

class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

if( 0 == n || 1 == n )
{
return;
}

int start = 0;
int end = n-1;
int tmp;

while( start < end )
{

if(A[start] != 0 )
{
while( start < end && A[end] != 0 )
{
end--;
}

if( start == end )
{
break;
}

tmp = A[start];
A[start] = A[end];
A[end] = tmp;
end--;
}

start++;
}


start--;
end = n-1;

while( start < end )
{
if(A[start] == 2 )
{
while( start < end && A[end] == 2 )
{
end--;
}

if( start == end )
{
break;
}

tmp = A[start];
A[start] = A[end];
A[end] = tmp;
end--;
}

start++;
}
}
};

posted @ 2013-06-18 21:04  NinaGood  阅读(201)  评论(0编辑  收藏  举报