A O(n) golang solution using state machine....


  • 0
    V
    const (
        BEGIN = iota
        ONEELEMENT
        NORMAL
    )
    func summaryRanges(nums []int) []string {
        ret := []string{}
        if len(nums) == 0 {
            return ret
        }
        state := BEGIN
        curs := ""
        curn := 0
        for _, n := range nums {
            switch state {
                case BEGIN:
                    state = ONEELEMENT
                    curs = strconv.Itoa(n)
                    curn = n
                case ONEELEMENT:
                    if n == curn+1 {
                        state = NORMAL
                        curn = n
                    } else {
                        ret = append(ret, curs)
                        curn = n
                        curs = strconv.Itoa(n)
                    }
                case NORMAL:
                    if n == curn+1 {
                        curn = n
                    } else {
                        curs += "->"
                        curs += strconv.Itoa(curn)
                        ret = append(ret, curs)
                        state = ONEELEMENT
                        curn = n
                        curs = strconv.Itoa(n)
                    }
            }
        }
        switch state {
            case BEGIN:
            case ONEELEMENT:
                ret = append(ret, curs)
            case NORMAL:
                curs += "->"
                curs += strconv.Itoa(curn)
                ret = append(ret, curs)
        }
        return ret
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.