• 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
        }
    }
    

      

  • 相关阅读:
    浏览器内核
    link和@import的区别
    跨域iframe如何通信
    数组、对象基本操作
    浏览器兼容性问题
    微信H5开发
    前端面试整理
    js多维数组转一维数组
    js实现继承
    javascript函数闭包(closure)
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/12838639.html
Copyright © 2020-2023  润新知