【leetcode】第75题 Sort Colors 题目+解析+JAVA代码
来源:互联网 发布:网站域名申请流程 编辑:程序博客网 时间:2024/06/05 09:06
【题目】
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.
这道题就是给了一个数组,其中都是乱序的0,1,2,让我们把乱序的0,1,2重新排列成0000……1111……2222.
这里用一个i来遍历数组,left和right分别保存0和2的边界,i在遍历过程中遇到0与left交换,遇到2与right交换。
【代码】
public void sortColors(int[] nums) { int left=0, right=nums.length-1; int i=0; while(i<=right){ if(nums[i]==1) i++; else if(nums[i]==0){ swap(nums,i,left); left++; i++; } else{ swap(nums,i,right); right--; } } } public void swap(int[] nums,int m,int n){ int temp=nums[m]; nums[m]=nums[n]; nums[n]=temp; }
阅读全文
0 0
- 【leetcode】第75题 Sort Colors 题目+解析+JAVA代码
- LeetCode算法题目:Sort Colors
- 【leetcode】第62题 Unique Paths 题目+解析+JAVA代码
- 【leetcode】第66题 Plus One 题目+解析+JAVA代码
- 【leetcode】第67题 Add Binary 题目+解析+JAVA代码
- 【leetcode】第69题 Sqrt(x) 题目+解析+JAVA代码
- 【leetcode】第70题 Climbing Stairs 题目+解析+JAVA代码
- 【leetcode】第72题 Edit Distance 题目+解析+JAVA代码
- 【leetcode】第77题 Combinations 题目+解析+JAVA代码
- 【leetcode】第78题 Subsets 题目+解析+JAVA代码
- [Leetcode] Sort Colors (Java)
- leetcode Sort Colors java
- [LeetCode][Java] Sort Colors
- leetcode:Sort Colors 【Java】
- Sort Colors leetcode java
- LeetCode 75(Sort Colors)Java
- Leetcode 75 Sort Colors
- LeetCode 75 Sort Colors
- Cpp-KMP模板
- 嵌入式linux系统支持usb wifi RTL8723BU
- HDU 6197array array array(简单dp)
- [笔记分享] [Exception] 用户空间异常之Call Stack AP使用
- [bzoj1782][Usaco2010 Feb]slowdown 慢慢游 dfs序+线段树
- 【leetcode】第75题 Sort Colors 题目+解析+JAVA代码
- U盘防拷贝选择隐大师
- iOS版本的APP已上线,但是AppStore里面按钮显示的是打开
- TP5.0实现无限极回复功能
- 浅谈CSRF攻击方式
- VTK环境配置中的一些问题
- 接Kafka数据比对不同hbase中数据
- 机器视觉Halcon——3. Halcon实例clip回形针方向识别
- [笔记]《操作系统精髓与设计原理》---(7)文件管理