75. Sort Colors(荷兰国旗问题 三指针)

 

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 swap(vector<int>& nums,int i ,int j) {
        int a = nums[i];
        nums[i] = nums[j];
        nums[j] = a;
    }
    void sortColors(vector<int>& nums) {
        int ptr = 0;
        for(int i = 0;i < nums.size();i++) {
            if(nums[i]==0) {
                swap(nums,i,ptr);
                ptr++;
            }
        }
        for(int i = ptr;i < nums.size();i++){
            if(nums[i]==1) {
                swap(nums,i,ptr);
                ptr++;
            }
        }
    }
};
复制代码

 

 

复制代码
class Solution {
public:
    void swap(vector<int>& nums,int i ,int j) {
        int a = nums[i];
        nums[i] = nums[j];
        nums[j] = a;
    }
    void sortColors(vector<int>& nums) {
        int low = 0;
        int high = nums.size()-1;
        int i = 0;
        while(i<=high) {
            if(nums[i]==0) {
                swap(nums,low,i);
                i++;
                low++;
            } else if (nums[i]==2){
                swap(nums,high,i);
                high--;

            } else {
                i++;
            }
        }
    }
};
复制代码

 

 

 

复制代码
 1 class Solution {
 2     public void sortColors(int[] nums) {
 3         int begin  = 0;
 4         int cur = 0;
 5         int end = nums.length-1;
 6         while(cur<=end){
 7             if(nums[cur]==2){
 8                 swap(nums,cur,end);
 9                 end--;
10             }
11             else if(nums[cur]==1){
12                 cur++;
13             }
14             else //(nums[cur]==0)
15             {
16                 if(nums[cur]!=nums[begin])
17                     swap(nums,cur,begin);
18                 begin++;
19                 cur++;
20             }
21         }
22     }
23     private void swap(int[] nums,int i ,int j){
24         int temp;
25         temp = nums[i];
26         nums[i] = nums[j];
27         nums[j] = temp;
28     }
29 }
复制代码

 

posted @   乐乐章  阅读(204)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示