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不做处理。
代码:
另一种平移插入法:
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;
}
}
};
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 进行排序
- Linux Shell - 如何使用sort与uniq命令删除重复的文本行
- Redis sort 排序命令详解
- 批处理命令教学之字符串排序(sort)
- mysql Sort aborted: Out of sort memory, consider increasing server sort buffer size的解决方法
- C++ 关于STL中sort()对struct排序的方法
- C#中Arraylist的sort函数用法实例分析
- Js中sort()方法的用法
- js采用concat和sort将N个数组拼接起来的方法
- 如何写JS数组sort的比较函数
- javascript中sort()的用法实例分析
- 详解Matlab中 sort 函数用法
- js模拟实现Array的sort方法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- js表数据排序 sort table data
- javascript 数组排序函数sort和reverse使用介绍
- JavaScript Table排序 2.0 (更新)
- js中数组(Array)的排序(sort)注意事项说明
- Javascript数组的排序 sort()方法和reverse()方法
- Java数据结构及算法实例:插入排序 Insertion Sort