您的位置:首页 > 编程语言 > Go语言

75. Sort Colors --- one-pass algorithm --- leetcode算法笔记

2016-06-23 10:20 447 查看
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

思路:遍历数组元素,遇到0往数组头部交换,遇到2往数组尾交换,1不做处理。

代码:

public void sortColors(int[] nums) {
int index1 = 0 ;
int index2 = nums.length - 1;
for(int i = 0 ; i <= index2 ;){
if(nums[i] == 0){
if(index1 < i){
nums[i] = nums[index1] ;
nums[index1] = 0 ;
}
index1 ++ ;
i ++ ;
}else if(nums[i] == 2){
while(i <= index2 && nums[index2] == 2) index2 -- ;
if(i < index2){
nums[i] = nums[index2] ;
nums[index2] = 2 ;
index2 -- ;
}
}else i++ ;
}
}


另一种平移插入法:

class Solution {
public:
void sortColors(int A[], int n) {
int i = -1;
int j = -1;
int k = -1;
for(int p = 0; p < n; p ++)
{
//根据第i个数字,挪动0~i-1串。
if(A[p] == 0)
{
A[++k] = 2; //2往后挪
A[++j] = 1; //1往后挪
A[++i] = 0; //0往后挪
}
else if(A[p] == 1)
{
A[++k] = 2;
A[++j] = 1;
}
else
A[++k] = 2;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Sort Colors one-pass