zoukankan      html  css  js  c++  java
  • Citrix 挂经思考

    【calculate region:占据长度的总和】

    思路:我自己想的是存map,但是元素的个数未知。别人写的是用stack,我没想到。说明stack在排序的时候很好用啊。

    心得:多给点时间查答案的话,还是能查到的。

    参考:https://leetcode.com/discuss/general-discussion/534205/interview-question

    fun calculateRegion(arr: IntArray): Int {
        val left = getNeightbourSum(arr)
        val right = getNeightbourSum(arr.reverse())
        return left + right + arr.size
    }
    
    fun getNeightbourSum(arr: IntArray): Int {
        val s = Stack<IntArray>()
        var ans = 0
        for(i in 0 until arr.size) {
           var count = 0 
           while(stack.isEmpty().not() && stack.peek()[0] <= arr[i]) {
               count += stack.peek()[1] + 1
               stack.pop()
           }  
           ans += count
           stack.add(intArrayOf(arr[i], count))
        }
        return ans
    }
    
    // [1, 1, 1, 1]
    // left = 0 + 1 + 2 + 3
    // right = 0 + 1 + 2 + 3
    // ans = 6 + 6 + 4(size of a array) = 16
  • 相关阅读:
    HQL语句中类的别名语法以及作用?
    C#面向对象
    c#异步编程一
    c#接口
    c#Socket通信基本使用
    c#FTP基本使用
    c#XML的基本使用
    c#装箱与拆箱
    c#数组与集合
    c#中for与foreach的使用
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14201230.html
Copyright © 2011-2022 走看看