Leetcode: Sort Colors
来源:互联网 发布:手机淘宝店招尺寸像素 编辑:程序博客网 时间:2024/06/11 11:23
Question
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.
click to show follow up.
Hide Tags Array Two Pointers Sort
Analysis
In this problem, we don′t need to know the order of all 0, 1, and 2. It requires us to modify nums in-place. we need to know the end of nums, the end of 0s. In this case, when if we encounter 0, we put it at the begining of nums; if encounter 1, we put it after redp; if encounter 2, we do nothing.
My Solution
class Solution: # @param {integer[]} nums # @return {void} Do not return anything, modify nums in-place instead. def sortColors(self, nums): redp = -1; end = -1; while(end<len(nums)-1 and len(nums)>0): if nums[end+1]==0: del nums[end+1] nums.insert(0,0) redp = redp + 1 elif nums[end+1]==1: del nums[end+1] nums.insert(redp+1, 1) end = end + 1
- 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
- maven工程检查依赖包冲突的命令
- libevent源码深度剖析十
- ubuntu wordpress 插件上传 ftp 用户密码设置
- 虚拟机安装linux之网络配置
- libevent源码深度剖析十一
- Leetcode: Sort Colors
- 日拱一卒(五十六)
- 【第五章】Spring表达式语言 之 5.4在Bean定义中使用EL—跟我学spring3
- 安卓齿轮动画
- django shell python-mysqldb
- 代理的作用
- Linux内核符号表
- 对象的比较Comparable与Comparator
- 64位Win8系统,Pl/SQL连接Oracle设置