您的位置 首页 golang

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:

文章来源:智云一二三科技

文章标题:Golang刷题Leetcode 75. Sort Colors

文章地址:https://www.zhihuclub.com/97521.shtml

关于作者: 智云科技

热门文章

网站地图