Sort Colors
来源:互联网 发布:mysql 系统错误1067 编辑:程序博客网 时间:2024/06/10 06:22
* 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.
题目的要求就是把一个0,1,2散乱的数组,变成先都是0,再到都是1,再到都是2的数组。
我采用的方式是,统计出0和1的个数,分别为N0,N1。数组总体个数是N,把[0,N0)中的非0元素和[N0,N)中的0元素对调。再把[N0,N0+N1)中的非1元素和[N0+N1,N)中的1元素对调。
class Solution {public: void sortColors(vector<int>& nums) { int num_0=0; int num_1=0; for(int i=0;i<nums.size();i++){ if(nums[i]==0) num_0++; if(nums[i]==1) num_1++; } int j=num_0; for(int i=0;i<num_0;i++){ if(nums[i]!=0){ for(;j<nums.size();j++){ if(nums[j]==0){ int temp=nums[j]; nums[j]=nums[i]; nums[i]=temp; break; } } } } j=num_0+num_1; for(int i=num_0;i<num_0+num_1;i++){ if(nums[i]!=1){ for(;j<nums.size();j++){ if(nums[j]==1){ int temp=nums[j]; nums[j]=nums[i]; nums[i]=temp; break; } } } } }};
1 0
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- 实现JS中的 replaceAll 方法
- 【linux】如何查看文件的创建、修改时间
- 系统学习深度学习(二十二)--CNN经典模型总结
- 石子游戏 (SG函数)
- 简单的制作标定板的程序
- Sort Colors
- Tesseract-OCR ---样本训练
- 详细的键盘键值表
- 编写可维护的JavaScript学习笔记(一)
- B+树
- Java异常捕获相关
- 【MYSQL】关于服务启动1067错误解决思路
- 关于两种复合类型--引用和指针以及const常量限定符的一些总结
- 如何使JavaScript更高效