Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Autosaved

...

https://leetcode.com/problems/sort-colors/

Status
colourBlue
title待复习

遍历两次

先把所有 2 移动到最后、再把所有 0 移动到最后

Code Block
languagego
func sortColors(nums []int)  {
    i, j := 0, len(nums)-1
    for i <= j {
        if nums[i] == 2 {
            nums[i], nums[j] = nums[j], nums[i]
            j--
        } else {
            i++
        }
    }


    i=0
    for i <= j {
        if nums[i] == 1 {
            nums[i], nums[j] = nums[j], nums[i]
            j--
        } else {
            i++
        }
    }
}

遍历一次

Code Block
languagego
func sortColors(nums []int)  {
    p0, p2 := 0, len(nums)-1

    p := 0
    for p <= p2 {
        if nums[p] == 0 {
            nums[p0], nums[p] = nums[p], nums[p0]
            p0++
        } else if nums[p] == 2 {
            nums[p], nums[p2] = nums[p2], nums[p]
            p2--
        } else {
            p++
        }

        if p < p0 {
            p = p0
        }
    }
}