Leetcode-- Sort Colors
来源:互联网 发布:算法第四版 kindle 编辑:程序博客网 时间:2024/05/29 03:41
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.
Note:
You are not suppose to use the library's sort function for this problem.
解决思路:此题要求说白了就是将乱序的数组按照升序进行排列,而且在排序的过程中是一个稳定的过程,即要求为稳定排序算法。
像常见的稳定排序算法有好多,比如插入排序,冒泡排序等等。下面附上插入排序的代码:
class Solution {public: void sortColors(int A[], int n) { int i,j; int temp; for(i=0;i<n;++i) { temp = A[i]; j=i-1; while(j>=0 && temp<A[j]) { A[j+1] = A[j]; --j; } A[j+1] = temp; } }};当然,该排序算法时间复杂度为O(n*logn)。
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- 翻译经典之《Cisco Lan Switching》第六章 理解生成树(五):生成树初始化收敛三部曲
- CF 245H Queries for Number of Palindromes
- 在源代码中的空格及列表问题
- YT14-HDU-求1/n的第m位数
- spring集成memcached示例二
- Leetcode-- Sort Colors
- 黑苹果恢复方法。
- 英雄会在线编程题目(请大家不吝赐教)
- spring集成memcached示例一
- JavaScript中的标签语句
- Android 应用实现多进程
- 非SPJ的优化
- Eddy's 洗牌问题
- 怪怪的读音, 程序员的缩写单词