Skip to content

Latest commit

 

History

History
40 lines (37 loc) · 1.06 KB

927三等分.md

File metadata and controls

40 lines (37 loc) · 1.06 KB

每个部分的1的数量相等

func threeEqualParts(arr []int) []int {
    invalid := []int{-1, -1}
    ones := make([]int, 0, len(arr))
    for i, n := range arr { // 记录1出现的次数和位置
        if n == 1 {
            ones = append(ones, i)
        }
    }
    if len(ones) == 0 { // 没有1时随便切割
        return []int{0, len(arr)-1}
    }
    if len(ones) % 3 != 0 { // 不能被3整除,无法切割
        return invalid
    }

    oneCount := len(ones) / 3
    start1, start2, start3 := ones[0], ones[oneCount], ones[oneCount * 2]
    sectionLen := len(arr) - start3

    s1, s2, s3 := arr[start1 : start1 + sectionLen], arr[start2 : start2 + sectionLen], arr[start3:]
    if !isValid(s1, s2, s3) {
        return invalid
    }
    return []int{start1 + sectionLen - 1, start2 + sectionLen}
}

func isValid(s1, s2, s3 []int) bool {
    if len(s1) != len(s2) || len(s2) != len(s3) {
        return false
    }
    for i := 0; i < len(s1); i++ {
        if s1[i] != s2[i] || s2[i] != s3[i] {
            return false
        }
    }
    return true
}