75. Sort Colors(荷兰国旗问题 三指针)
2024-10-21 03:35:42
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.
Note:
You are not suppose to use the library's sort function for this problem.
三个指针 lo =cur =0,hi =n-1
a[cur]==0: if(lo==cur) cur++ lo++
else: swap(lo,cur) lo++
class Solution {
public void sortColors(int[] nums) {
int begin = 0;
int cur = 0;
int end = nums.length-1;
while(cur<=end){
if(nums[cur]==2){
swap(nums,cur,end);
end--;
}
else if(nums[cur]==1){
cur++;
}
else //(nums[cur]==0)
{
if(nums[cur]!=nums[begin])
swap(nums,cur,begin);
begin++;
cur++;
}
}
}
private void swap(int[] nums,int i ,int j){
int temp;
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
最新文章
- TRF7960天线参数试验
- Android_Spinner_example
- Linux下使用openvpn客户端
- awk-模式匹配
- tls session resumption
- php基础。php与js的不同
- 巧用FineReport搭建成本管控监测系统
- python3元组
- Android/Linux boot time分析优化
- URAL 1183 Brackets Sequence
- python-day54--前端之js-DOM对象
- 【bzoj2693】jzptab 莫比乌斯反演+线性筛
- 关于createTextRange和createRange的一些用法【转】
- springmvc 路由
- 配置ntpd时钟同步服务
- hdu 1087 简单dp
- Jsp 公用标签库
- Spark源码分析 &ndash; Checkpoint
- Python中的数据结构 --- 元组(tuple)、字典(tuple)
- web.xml中不同版本的servlet头以及版本控制