75. Sort Colors--数组排序
来源:互联网 发布:mac画流程图 编辑:程序博客网 时间:2024/05/22 13:34
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.
用0,1,2,分别代表红色,白色和蓝色,按照红白蓝的顺序排序,并且相同的颜色要相邻,所以这道题是对一个含有0,1,2三个元素的数组排序即可,但是不能调用排序函数Arrays.sort(),所以需要扫描两遍数组,第一次计数,记录每个数字出现的次数,第二次给数组赋值,代码如下:
if(nums.length<2){return;} int count0=0,count1=0,count2=0; for(int i=0;i<nums.length;i++){ if(nums[i]==0){count0++;} if(nums[i]==1){count1++;} if(nums[i]==2){count2++;} } for(int j = 0;j<count0;j++){ nums[j]=0; } for(int k = 0;k<count1;k++){ nums[k+count0]=1; } for(int l=0;l<count2;l++){ nums[l+count0+count1]=2; }但是这种写法效率很低==在网上找了另一种方法,直接平移,当数组中的数字为0,时,数组中的0,1,2都向后平移一位,当数字为1时,1和2向后移动一位,数字为2时,仅2向后移一位,虽然这种方法效率也不高==但是只对数组扫描了一遍,代码如下:
int len = nums.length;int j=-1,k=-1,n=-1;for(int i=0;i<len;i++){if(nums[i]==0){nums[++n]=2;nums[++k]=1;nums[++j]=0;}else if(nums[i]==1){nums[++n]=2;nums[++k]=1;}else{nums[++n]=2;}}
阅读全文
0 0
- 75. Sort Colors--数组排序
- 【LeetCode】Sort Colors 数组排序
- [leetcode] 【排序】 75. Sort Colors
- [leetcode-排序]--75. Sort Colors
- 75. Sort Colors 快速排序
- LeetCode 75. Sort Colors(颜色排序)
- LeetCode-75. Sort Colors (JAVA)三色排序
- 【leetcode 数组】Sort Colors
- Sort Colors 颜色排序
- 【排序】Sort Colors
- LeetCode Sort Colors(排序)
- Sort Colors 三色排序
- LeetCode-Sort Colors-排序
- 【Sort】75. Sort Colors(计数排序、荷兰国旗问题)
- 数组——sort colors
- Sort Colors 排序颜色 @LeetCode
- leetcode:sort colors排序颜色
- Sort Colors 哈希排序
- 深度学习论文随记(一)---AlexNet模型解读
- bootstrap-collapse.js 之无法实现折叠效果
- Eclipse字体颜色控制
- 两种方式实现java Md5加密
- Echars 生成图表宽高问题
- 75. Sort Colors--数组排序
- Android 开源网络框架(Android-Async-Http、Volley、OkHttp3、Retrofit2.0)对比
- vs2010怎么将生成的exe文件拷贝到指定文件夹中
- 极乐技术周报(第十七期)
- linux新加一个硬盘,自动挂载
- 通过Base64加密解密解决RSA中文解密乱码问题
- JS组件系列——表格组件神器:bootstrap table(三:终结篇,最后的干货福利)
- 使用MVP模式及retrofit框架实现登录
- 启动和停止MySQL