[leetcode-75]Sort Colors(C)
来源:互联网 发布:java list 随机排序 编辑:程序博客网 时间:2024/05/20 15:11
问题描述:
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有多少个即可。这样在排序的时候,只要生成足够的0,足够的1,足够的2即可。时间复杂度为O(n)
代码如下:0ms
void sortColors(int* nums, int numsSize) { //使用桶排序 int count[3]; for(int i = 0;i<3;i++){ count[i] = 0; } for(int i = 0;i<numsSize;i++){ int val = nums[i]; count[val]++; } int numsIndex = 0; for(int i = 0;i<3;i++){ int countt = count[i]; for(int j = 0;j<countt;j++){ nums[numsIndex++] = i; } }}
0 0
- [leetcode-75]Sort Colors(C)
- [C语言][LeetCode][75]Sort Colors
- Leetcode 75 Sort Colors
- LeetCode 75 Sort Colors
- [leetcode 75] Sort Colors
- LeetCode 75 Sort Colors
- leetcode-75 Sort Colors
- [leetCode 75] Sort Colors
- LeetCode 75 Sort Colors
- leetcode || 75、Sort Colors
- Leetcode 75Sort Colors
- Sort Colors - LeetCode 75
- leetcode 75:Sort Colors
- LeetCode(75) Sort Colors
- Leetcode # 75 Sort Colors
- leetcode 75: Sort Colors
- Leetcode#75||Sort Colors
- Leetcode 75:Sort Colors
- vim 快捷键(图)
- 在android 输入框中判断表情
- telnet退出命令
- 知名的第三方开源库
- Problem C: P1053
- [leetcode-75]Sort Colors(C)
- Mavan配置
- kanban工具
- C# ref和out参数的使用
- jRTPlib支持多网卡,支持TCP
- IOS XMPP的实践
- 给图像添加探照灯效果
- 微信公众平台开发整理
- VS2002(VC7) 新建arx项目