Leetcode no. 75
来源:互联网 发布:linux删除文件权限不够 编辑:程序博客网 时间:2024/05/22 03:47
75. 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.
click to show follow up.
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 an one-pass algorithm using only constant space?
public class Solution { public void sortColors(int[] nums) { int left=0, right= nums.length-1; for (int i = 0; i <= right; i++) { if (nums[i]==0){ nums[i]= nums[left]; nums[left++]=0; } else if (nums[i]== 2){ nums[i--]= nums[right]; nums[right--]= 2; } } }}
0 0
- Leetcode no. 75
- Leetcode NO.75 Sort Colors
- LeetCode No.75 Sort Colors
- LeetCode--No.75--Sort Colors
- LeetCode No.11 ~No.12
- Leetcode NO.78 Subsets
- Leetcode NO.77 Combinations
- Leetcode NO.46 Permutations
- 【leetcode】No. 235 LCABST
- LeetCode no. 35
- Leetcode no. 37
- Leetcode no. 279
- Leetcode no. 335
- Leetcode no. 283
- Leetcode no. 181 (sql)
- Leetcode no. 40
- Leetcode no. 238
- Leetcode no. 26
- 第十一周项目1-点-圆-圆柱类族的设计(2)
- poj1466——Girls and Boys(最大独立点集)
- [一起学Hive]之五-Hive的视图和分区
- c++第五次上机作业
- ASP.NET的事件模型
- Leetcode no. 75
- iOS私有API的了解
- 设计模式C++学习笔记之十(Builder建造者模式)
- sftp免密登录
- 内存管理(malloc和free用法)
- 纪念一下
- [swift学习之四]结构体练习
- 设计模式C++学习笔记之十一(Bridge桥梁模式)
- API网关(API Gateway)