zoukankan      html  css  js  c++  java
  • [Leetcode] Candy

    There are N children standing in a line. Each child is assigned a rating value.

    You are giving candies to these children subjected to the following requirements:

    • Each child must have at least one candy.
    • Children with a higher rating get more candies than their neighbors.

    What is the minimum candies you must give?

    Solution:

    基本思路就是进行两次扫描,一次从左往右,一次从右往左。第一次扫描的时候维护对于每一个小孩左边所需要最少的糖果数量,存入数组对应元素中,第二次扫描的时候维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中。这样两遍扫描之后就可以得到每一个所需要的最最少糖果量,从而累加得出结果。方法只需要两次扫描,所以时间复杂度是O(2*n)=O(n)。空间上需要一个长度为n的数组,复杂度是O(n)。

     1 public class Solution {
     2     public int candy(int[] ratings) {
     3         if(ratings.length==0)
     4             return 0;
     5         int N=ratings.length;
     6         int[] candies=new int[N];
     7         candies[0]=1;
     8         for(int i=1;i<N;++i){
     9             if(ratings[i]>ratings[i-1]){
    10                 candies[i]=candies[i-1]+1;
    11             }else{
    12                 candies[i]=1;
    13             }
    14         }
    15         for(int i=N-2;i>=0;--i){
    16             if(ratings[i]>ratings[i+1]&&candies[i]<=candies[i+1])
    17                 candies[i]=candies[i+1]+1;
    18         }
    19         int result=0;
    20         for(int iCandy:candies){
    21             result+=iCandy;
    22         }
    23         return result;
    24     }
    25 }
  • 相关阅读:
    计算几何 判断点在直线的左右哪一侧
    图论 迪杰斯特拉dijkstra求最短路径
    图论 用prim法求最小生成树
    图论 邻接表广搜
    图论 用广搜搜邻接矩阵
    图论 邻接表建图+dfs
    图论 邻接矩阵建图+dfs遍历
    HDU 2141 二分查找
    二叉树知道前序和中序求后序,知道中序后序求中序
    二叉树的查找
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4118683.html
Copyright © 2011-2022 走看看