# leetcode 75. Sort Colors-颜色排序|双指针

【思路1-Python】-双指针|T=O(n)|M=O(1)

class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
head, tail, i = 0, len(nums)-1, 0
while i <= tail :
if nums[i] == 0 :
i += 1
elif nums[i] == 1 : i += 1
else :
nums[i], nums[tail] = nums[tail], nums[i]
tail -= 1
86 / 86 test cases passed. Runtime: 52 ms  Your runtime beats 46.69% of pythonsubmissions.

【思路2-Java】-双指针|T=O(n)|M=O(n)

public class Solution {
public static void sortColors(int[] nums) {
int len = nums.length;
int[] tmp = new int[len];
for(int i = 0; i < len; i++)      //初始化数组为1
tmp[i] = 1;
int first = 0, last = len - 1;
for(int i=0; i<len; i++)          //遍历一次
if(nums[i] == 0) tmp[first++] = 0;
else if(nums[i] == 2) tmp[last--] = 2;
for(int i=0; i<len; i++) nums[i] = tmp[i];
}
}
86 / 86 test cases passed. Runtime: 1 ms  Your runtime beats 4.38% of javasubmissions.

#### Leetcode题目分类：类型+难易

2015-04-15 16:16:48

#### LeetCode 75. Sort Colors（三颜色排序→K颜色排序）

2018-03-26 16:29:28

#### 排颜色问题——数组 leetcode lintcode

2015-06-08 09:11:15

#### leetCode 75.Sort Colors (颜色排序) 解题思路和方法

2015-07-19 16:38:00

#### LeetCode 75 分类颜色

2018-05-11 22:53:26

#### leetcode 75 分类颜色

2018-05-09 19:30:29

#### 九章算法面试题70 排颜色II sort colors

2015-05-18 05:54:37

#### Leetcode 75. 分类颜色

2018-05-15 17:00:20

#### LeetCode（75） Sort Colors

2015-09-17 20:00:39

#### 【LeetCode】75.Sort Colors（Medium）解题报告

2018-02-23 22:21:41