七叶笔记 » golang编程 » Golang刷题Leetcode 75. Sort Colors

Golang刷题Leetcode 75. Sort Colors

题目: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.

0,1,2代表三个颜色,给一个数组里面包括这三个颜色,按照0,1,2的顺序排序

思路

如果不要求时间和空间复杂度,直接排序肯定是可以的

code

func swap(nums []int,i,j int){
 tmp := nums[i]
 nums[i] = nums[j]
 nums[j] = tmp
}
func sortColors(nums []int) {
 l,i,r := 0,0,len(nums)-1
 for i<=r{
 if nums[i] == 0{
 swap(nums,i,l)
 i++
 l++
 }else {
 if (nums[i] == 1){
 i++
 }else{
 swap(nums,i,r)
 r--
 }
 }
 }
}
 

更多内容请移步我的repo:

相关文章