题解 | #枪打出头鸟#

枪打出头鸟

http://www.nowcoder.com/practice/1504075c856248748ca444c8c093d638

题目解析

图片说明
每个人会击中前面第一个比自己高的人,如上图所示。
用栈来存储数组的递减的子序列,从而找到每一个被击中的人。
遍历数组时,

  • 若栈顶元素大于当前数组值,则栈顶元素被击中,将数字值入栈
  • 若栈顶元素值小于或等于数组值,则将栈顶元素弹出,判断新的栈顶值大小。若栈为空,说明没有比当前值大的,将当前数数组值入栈。

    JAVA代码

    public long solve (int n, int[] a) {
          // write code here
          if(n <= 1){
              return 0;
          }
          long ans = 0;
          Stack<Integer> stack = new Stack<>();
          // i 表示第i个人
          for(int i = 1;i <= n;i++){
              while(!stack.isEmpty() && a[i - 1] >= a[stack.peek() - 1]){
                  stack.pop();
              }
              if(!stack.isEmpty()){
                  ans += stack.peek();
              }
              stack.push(i);         
          }        
          return ans;
      }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务