LeetCode: Sorted Color
2024-09-21 12:00:06
Title:
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.
直观的解法是使用计数排序
class Solution {
public:
void sortColors(vector<int>& nums) {
int *c = new int [];
memset(c,,sizeof(int)*);
for (int i = ; i < nums.size(); i++){
c[nums[i]]++;
}
nums.clear();
for (int i = ; i < ; i++){
for (int j = ; j < c[i]; j++){
nums.push_back(i);
}
}
}
};
也可以遍历一次就能得到结果,使用3个下标,分别指向0,1,2对应的下标位置。可以这么理解,最左边是0,最右边是2,中间遇到1不用管
class Solution {
public:
void sortColors(int A[], int n) {
if(n <= ) return;
int start = -, end = n;
int p = ;
while(p < n && start < end){
if(A[p] == ){
if(p > start) swap(A, ++start, p);
}else if(A[p] == ){
if(p < end) swap(A, p, --end);
}else ++p;
}
}
private:
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
};
最新文章
- c#使用多线程的几种方式示例详解
- day22、模块-basedir、os、json模块、pickle和正则模块。
- 微信公众平台开发(68)苹果IMEI查询
- Spring shiro使用
- 各式 Web 前端開發工具整理
- 如何搭建一个angularJS应用
- jQuery UI Widget(1.8.1)工作原理--转载
- 使用javaservice 将jboss 注册为服务
- 不安装oracle客户端,如何运行sqlplus
- YII 框架在 MAC OS下 连接数据库失败 提示 DB connection: SQLSTATE[HY000] [2002]
- SQL 数据库基本知识
- bzoj1834 [ZJOI2010]网络扩容
- Web框架django[Form]组件
- ONCOCNV软件思路分析之control处理
- ES2018新特性(译文)
- Batch入门教程丨第一章:部署与Hello World!(上)
- 什么是javabean及其用法(转)
- Thing in java 第5章,初始化和清理,练习题答案
- ==,hashcde, equals(一)
- Js高级 事件 对象