904. 水果成篮

https://leetcode-cn.com/problems/fruit-into-baskets/

暴力法:超时

func totalFruit(tree []int) int {
    res := 0 
    n := len(tree)
    i,j := 0,0
    for i=0;i<n;i++{
        pre1,pre2 := -1,-1
        for j=i;j<n;j++{
            if pre1 == -1 || pre1 == tree[j]{
                pre1 = tree[j]
                continue
            }else if pre2 == -1 || pre2 == tree[j]{
                pre2 = tree[j]
                continue
            }else{
                if tree[j] == pre1 || tree[j] == pre2{
                    continue
                }
                res = MAX(res,j-i)
                break
            }
        }
        res = MAX(res,j-i) 
    }
    return res
}

func MAX(i,j int) int{
    if i<j{
        return j
    }else{
        return i
    }
}

  用滑动窗口优化下时间复杂度:最主要一点,

tRight := right-1
pre1 = tree[tRight]
pre2 = tree[right]
func totalFruit(tree []int) int {
    res := 0 
    n := len(tree)
    left,right := 0,0
    pre1,pre2 := -1,-1
    for right < n{
        if pre1 == -1 || pre1 == tree[right]{
            pre1 = tree[right]
            right++
            continue
        }else if pre2 == -1 || pre2 == tree[right]{
            pre2 = tree[right]
            right++
            continue
        }else{
            res = MAX(res,right-left)
            tRight := right-1
            pre1 = tree[tRight]
            pre2 = tree[right]
            for tree[tRight] == pre1{
                tRight--
            }
            left = tRight+1
        }
    }
    res = MAX(res,right-left)
    return res
}

func MAX(i,j int) int{
    if i<j{
        return j
    }else{
        return i
    }
}

  

posted on 2020-05-06 20:16  wsw_seu  阅读(305)  评论(0编辑  收藏  举报

导航