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.

 

给定一个包含红,白,蓝且长度为n的数组,将数组元素进行分类使同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数0,1和2分别代表红,白,蓝。

 

复制代码
 1     private void swap(int[] nums,int left,int right)
 2     {
 3         int temp = nums[left];
 4         nums[left] = nums[right];
 5         nums[right] = temp;
 6     }
 7     
 8     public void sortColors(int[] nums) {
 9         int second=nums.length-1, zero=0;
10         for (int i=0; i<=second; i++) {
11             while (nums[i]==2 && i<second) swap(nums,i,second--);
12             while (nums[i]==0 && i>zero) swap(nums,i,zero++);
13         }  
14     }
复制代码

 

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