75.颜色排序
来源:互联网 发布:非线性优化 编辑:程序博客网 时间:2024/04/27 19:17
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.
测试代码(c++):
class Solution {public: void sortColors(vector<int>& nums) { int left = 0; int right = nums.size()-1; int i = 0; int time = nums.size(); int flag = 1; while(i>=left&&i<=right) { if(nums[i]==0) { swap(nums[i],nums[left]); left++; i = left; flag = 1; }else if(nums[i]==1) { i += flag; }else{ swap(nums[i],nums[right]); right--; i = right; flag = -1; } cout<<left; } }};
性能:
参考答案(C++):
class Solution {public: void sortColors(vector<int>& nums) { int i = 0 , j = 0 , k = 0; for(int v : nums){ if(v == 0){ nums[k++] = 2; nums[j++] = 1; nums[i++] = 0; } else if(v == 1){ nums[k++] = 2; nums[j++] = 1; } else nums[k++] = 2; } }};
性能:
参考答案(python):
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = j = 0 for k in xrange(len(nums)): v = nums[k] nums[k] = 2 if v < 2: nums[j] = 1 j += 1 if v == 0: nums[i] = 0 i += 1
性能:
阅读全文
0 0
- 75.颜色排序
- LeetCode 75. Sort Colors(颜色排序)
- 按照颜色进行排序
- Sort Colors 颜色排序
- Lintcode 颜色排序2
- leetCode 75.Sort Colors (颜色排序) 解题思路和方法
- leetcode 75. Sort Colors-颜色排序|双指针
- Leetcode刷题记——75. Sort Colors(颜色排序)
- Sort Colors 排序颜色 @LeetCode
- leetcode:sort colors排序颜色
- leetcode【第十三周】颜色排序
- IOS--颜色转换 数组排序 事件转换
- 在Excel2003中按颜色进行排序
- 单元格排序+行颜色变化(DHTML)
- IOS--颜色转换 数组排序 事件转换
- LeetCode 75 Sort Colors(颜色排序)
- [Java语言] Sort Colors 颜色排序
- 数组------荷兰国旗问题(颜色排序)
- svn版本管理软件——创建svn私人仓库
- Java常见面试题—实现多线程的三种方式
- CY7C68013A控制传输
- 解决NLog输出中文为乱码问题
- .net中的Queue和Stack,及各种list集合使用
- 75.颜色排序
- 人和人最大的差别不是技术上的高低,而是你的人生观价值观
- redhat-kernel-kdump-crash----内核dump文件分析
- for循环删除数组时的问题
- 如何学习网络编程
- 库文件如何加载到内存?程序编译如何找到这些库文件并加载?
- SDWebImage的实现原理
- Linux系统中的文件的s权限
- Get和Post请求的区别