diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 4b36764..a15632b 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -7266,3 +7266,53 @@ func relativeSortArray(arr1 []int, arr2 []int) []int { return result } ``` + +## day107 2024-06-12 + +### 75. Sort Colors + +Given an array nums 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. + +We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + +You must solve this problem without using the library's sort function. + +![0612gdOHBokPpjjH](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0612gdOHBokPpjjH.png) + +### 题解 + +本题只有0,1,2三个数, 对只包含这三个数的数组进行排序, 直接在原数组上修改, 充分考虑题目条件, 没有必要使用排序算法来排序, 当题目中只有两个数的时候, 对整个数组排序相当于通过两变量交换将小的数都交换到前面, 大的都交换到后面. 现在有三个数, 则通过只需通过交换位置将所有的2都放到数组末尾, 将所有的0放到数组开头, 1自然就位于中间位置. 交换的思路也很简单, 通过两个变量分别标记被移到数组开头的0的个数和移到数组末尾的2的个数, 遇到0就将其移到之前的0的后面并将开头0的个数加一, 对2同理. + +### 代码 + +```go +func sortColors(nums []int) { + zeros := 0 + twos := len(nums) - 1 + Loop: + for i, value := range nums{ + if value == 0{ + nums[i],nums[zeros] = nums[zeros],nums[i] + zeros++ + }else if value == 2{ + for twos >= 0 && nums[i] == 2{ + if i >= twos{ + break Loop + } + fmt.Println() + nums[i],nums[twos] = nums[twos],nums[i] + twos-- + } + if nums[i] == 0{ + nums[i],nums[zeros] = nums[zeros],nums[i] + zeros++ + } + } + } + return +} +``` + +### 总结 + +思路是正确的, 但在实现时有一些细节要注意, 如遇到2将其交换到末尾时, 如果被交换过来的数也是2则要继续将其移到末尾, 直到交换过来的数不是2或者已经将当前下标后面的所有数都交换为2为止.