DinghaoLI / Coding-Interviews-Golang

剑指offer的Go实现 完整版
MIT License
400 stars 104 forks source link

最后的数组的相对位置是变了啊 #3

Open siyalight opened 4 years ago

siyalight commented 4 years ago

https://github.com/DinghaoLI/Coding-Interviews-Golang/blob/cd7e47ea581265709ed5b1fb75c073c93dfdab34/014-%E8%B0%83%E6%95%B4%E6%95%B0%E7%BB%84%E9%A1%BA%E5%BA%8F%E4%BD%BF%E5%A5%87%E6%95%B0%E4%BD%8D%E4%BA%8E%E5%81%B6%E6%95%B0%E5%89%8D%E9%9D%A2/problem014.go#L21

songjiayang commented 4 years ago

确实变了,大概修改了一下:

package main

import (
    "fmt"
)

func main() {
    items := []int{1, 2, 3, 4}
    oddFirst(items)
    fmt.Println(items)
}

func oddFirst(s []int) {
    if len(s) < 2 {
        return
    }

    i, j := len(s)-2, len(s)-1
    for i >= 0 {
        if s[j]%2 == 0 {
            j--
        } else if s[i]%2 == 0 {
            temp := s[i]
            copy(s[i:j], s[i+1:j+1])
            s[j] = temp
            j--
            i--
        } else {
            i--
        }
    }
}

= >

[1 3 2 4]