Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-colors
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法1:遍历元素,把0调到数组的前面,把2调到数组后面,1不用处理:

 public void sortColors(int[] nums) {
int length = nums.length;
int temp,index;
index=0;
for(int i = 0; i < length; i++)
{
if(nums[i] == 0)
{
temp = nums[index];
nums[index++] = nums[i];
nums[i] = temp;
}
}
index=length - 1;
//这里其实可以加个限定条件,因为是从数组末端开始遍历的,当遍历到0的时候,就已经不用再往前遍历了,因此也可节省一丁点时间,不过好像问题并不大,需要优化的是内存方面。。。
for(int j = length - 1; j >= 0; j--)
{
if(nums[j] == 2)
{
temp = nums[index];
nums[index--] = nums[j];
nums[j] = temp;
}
} }

解法2:遍历计数0,1,2的个数,再把原数组重新赋值:

    public void sortColors(int[] nums) {
int length = nums.length;
int count = 0;
int count1 = 0;
int count2;
for(int i = 0; i < length; i++)
{
if(nums[i] == 0)
{
nums[count] = 0;
count++;
}
else if(nums[i] == 1)
{
count1++;
}
}
count2 = length - (count + count1); for(int i = count; i < count + count1; i++)
{
nums[i] = 1;
}
for(int i = count+count1; i < length; i++)
{
nums[i] = 2;
}
}

最新文章

  1. Maven的环境搭建及新建web项目
  2. C#_数据转换 实用方法
  3. Java基础之一组有用的类——使用Scanner对象(TryScanner)
  4. Linux下升级python版本
  5. [工具]前端自动化工具grunt+bower+yoman
  6. FPGA的SPI从机模块实现
  7. Linux上传下载文件命令
  8. TinyMce 使用初探
  9. odoo 配置文件
  10. [精华][推荐]CAS SSO单点登录服务端客户端实例
  11. 基于Material-Design的Gank-IO客户端
  12. 为CSDN博客添加站内搜索栏目
  13. 服务网关Zuul
  14. 2.7、CDH 搭建Hadoop在安装(使用向导设置群集)
  15. MVC扩展ModelBinder,通过继承DefaultModelBinder把表单数据封装成类作为action参数
  16. 2.2 The Object Model -- Reopening Classes and Instances
  17. 【BZOJ】1597 [Usaco2008 Mar]土地购买
  18. U3D安卓下OnApplicationQuit不执行的解决方法
  19. matplotlib绘制柱状图
  20. LinkedHashMap原理以及场景

热门文章

  1. Ubuntu 16 server 安装 tensorflow-GPU
  2. 第二篇 Flask的Response三剑客及两个小儿子
  3. opacity层叠问题
  4. GPS学习笔记
  5. js中关于执行的顺序及变量存放方式的一点记录
  6. P3976 [TJOI2015]旅游(未完成)
  7. NOIP 模拟19
  8. Wycieczki 线性代数
  9. 算法笔记codeup-Contest100000567
  10. LNMP+Redis架构部署