75. Sort Colors - LeetCode
Question

Solution
题目大意:
给一个数组排序,这个数组只有0,1,2三个元素,要求只遍历一遍
思路:
记两个索引,lowIdx初始值为0,highIdx初始值为nums.length - 1,遍历数组,如果是2就与highIdx处元素互换且highIdx—,如果是0就与lowIdx处元素互换且lowIdx++,i++,还剩一种情况就是1了,执行i++,循环结束条件是i<=highIdx
Java实现:
public void sortColors(int[] nums) {
int lowIdx = 0;
int highIdx = nums.length - 1;
int i = 0;
while (i <= highIdx) {
if (nums[i] == 2) {
int tmp = nums[highIdx];
nums[highIdx--] = nums[i];
nums[i] = tmp;
} else if (nums[i] == 0) {
int tmp = nums[lowIdx];
nums[lowIdx++] = nums[i];
nums[i++] = tmp;
} else {
i++;
}
}
}
75. Sort Colors - LeetCode的更多相关文章
- LeetCode 75. Sort Colors (颜色分类):三路快排
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...
- 75. Sort Colors(颜色排序) from LeetCode
75. Sort Colors 给定一个具有红色,白色或蓝色的n个对象的数组,将它们就地 排序,使相同颜色的对象相邻,颜色顺序为红色,白色和蓝色. 这里,我们将使用整数0,1和2分别表示红色, ...
- 刷题75. Sort Colors
一.题目说明 题目75. Sort Colors,给定n个整数的列表(0代表red,1代表white,2代表blue),排序实现相同颜色在一起.难度是Medium. 二.我的解答 这个是一个排序,还是 ...
- 【LeetCode】75. Sort Colors (3 solutions)
Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of t ...
- [LeetCode] 75. Sort Colors 颜色排序
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...
- LeetCode 75. Sort Colors(排序颜色)
Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...
- 【一天一道LeetCode】#75. Sort Colors
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- 【LeetCode】75. Sort Colors 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 计数排序 双指针 日期 题目地址:https://l ...
- Leetcode 75. Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...
随机推荐
- vuex基础详解
vuex入门 安装 vuex为我们提供了两种使用方法 直接引入 vuex下载地址:https://unpkg.com/vuex@2.0.0 下载之后用< script >标签包裹引入即可 ...
- ES6-11学习笔记--Symbol
Symbol:一种新的原始数据类型 声明方式: let s1 = Symbol() let s2 = Symbol() console.log(s1); // Symbol() console.l ...
- DB2表数据导出、导入及常用sql使用总结
一.DB2数据的导出: export to [path(例:D:"TABLE1.ixf)]of ixf select [字段(例: * or col1,col2,col3)] from ...
- vue日历(纯 js,没用任何插件和组件)
效果图: 代码: <template> <div class="calender"> <div class="top"> ...
- 93. 复原 IP 地址
做题思路or感想 这种字符串切割的问题都可以用回溯法来解决 递归三部曲: 递归参数 因为要切割字符串,所以要用一个startIndex来控制子串的开头位置,即是会切割出一个范围是[startIndex ...
- js知识梳理3:创建对象的模式探究
写在前面 注:这个系列是本人对js知识的一些梳理,其中不少内容来自书籍:Javascript高级程序设计第三版和JavaScript权威指南第六版,感谢它们的作者和译者.有发现什么问题的,欢迎留言指出 ...
- C++怎么实现多态?
C++通过函数重载或模板实现编译期多态(静态绑定),通过虚函数实现运行时多态(动态绑定). 1.函数重载 #include <stdio.h> int add(int a, int b) ...
- [个人配置] VSCode Better Comments 扩展配置、高亮注释插件
在VSCode IDE中,我的代码注释一般都有高亮颜色,那要怎么安装这个插件呢?
- 用js实现倒计时效果
首先获得两个时间的时间戳 var newdate = new Date('2021-01-22 21:25:00').getTime(); var olddate = new Date().getTi ...
- Java语言学习day12--7月11日
###16随机点名器代码实现 * A: 随机点名器案例代码 /* 随机点名器,集合改进 (学生的姓名和年龄) 现实中有学生这个事物,使用定义类的形式,描述学生事物 属性: 姓名,年龄 姓名存储了数组, ...