27-75. Sort Colors
时间:2019-06-18
本文章向大家介绍27-75. Sort Colors,主要包括27-75. Sort Colors使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
题目描述:
Given an array with n objects colored red, white or blue, sort them in-place 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.
Example:
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
Follow up:
- A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. - Could you come up with a one-pass algorithm using only constant space?
代码实现:
1 def sortColors(self, nums): 2 i = j = 0 3 for k in xrange(len(nums)): 4 v = nums[k] 5 nums[k] = 2 6 if v < 2: 7 nums[j] = 1 8 j += 1 9 if v == 0: 10 nums[i] = 0 11 i += 1
原文地址:https://www.cnblogs.com/tbgatgb/p/11043147.html
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Spring注解@Autowired源码分析
- 使用RecyclerView实现水平列表
- android实现记住用户名和密码以及自动登录
- Android碎片fragment实现静态加载的实例代码
- android异步消息机制 源码层面彻底解析(1)
- /undefinedcss/modules/layer/default/layer.css?v=3.1.1找不到的问题
- Android实现渐变启动页和带有指示器的引导页
- the input device is not a TTY. If you are using mintty, try prefixing the comma
- 【STM32F407】第13章 RL-TCPnet V7.X之创建多个TCP客户端
- RecyclerView实现列表倒计时
- wsl设置默认账户为root(ubuntu18.04)
- LeetCode No.14 最长公共前缀
- android异步消息机制 从源码层面解析(2)
- beego解决跨域问题:options请求、axios post请求跨域问题
- Android ListView列表实现倒计时