• 【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?

    本来是抱着找个水题刷一下的态度选择这个题的,但是各种错都郁闷了。。。。(可能也是因为开始的态度就不太对吧)。废话少说,看题:

    这个题的意思还真不是很清楚,最开始我的理解是n个号每个号至少分一个糖,而且排名高的要比排名低的多,觉得就上个排序就了事,nlogn的复杂度应该还是可以接受的吧。于是就开始狂WA了,有以下两个个原因,首先是对rating的理解错误,其实rating应该是数字越小越高,还有一个更加隐蔽的东西,就是它上面的那两个requirement很容易误导我们,第二个其实说的是每个rating高的人必须是比邻居高,也就是说对于和两边相等的我们可以分配一个就行了(这个是过了才领悟到,极其痛苦啊)。

    不过后来题目理解完了发现超时了,看来nlogn的算法还是不够优秀,于是就把排序扔了(后来才发现排序本就是错的)。在正确理解题目意思的情况直接扫两遍记录一下就行了。

    这里给出几组测试数据,也帮助一下同挂在这个地方的人。

    case1:input:[2,3,2]

        output:4

    case2:input:[1,2,2,2,3,2,1]

               output:11

    代码如下:

     1 class Solution {
     2 public:
     3     int candy(vector<int> &ratings) {
     4         if(ratings.empty()){
     5             return 0;
     6         }
     7         if(ratings.size()==1){
     8             return 1;
     9         }
    10         int l=ratings.size();
    11         int* temp=new int[l];
    12         temp[0]=1;
    13         for(int i=1;i<l;i++){
    14             if(ratings[i]>ratings[i-1]){
    15                 temp[i]=temp[i-1]+1;
    16             }
    17             else{
    18                 temp[i]=1;
    19             }
    20         }
    21 
    22         int ans=temp[l-1];
    23         for(int i=l-2;i>=0;i--){
    24             if(ratings[i]>ratings[i+1]&&temp[i+1]+1>temp[i]){
    25                 temp[i]=temp[i+1]+1;
    26             }
    27             ans+=temp[i];
    28         }
    29         return ans;
    30     }
    31 };
  • 相关阅读:
    FineReport自学习题第四题——图表
    SQL如何查询连续数字并且统计连续个数
    Arm Cortex-M3 MCU性能
    北汽蓝谷极狐阿尔法S与T
    长鑫存储DDR产品
    华虹宏力芯片制造主流工艺技术
    传统编译器与神经网络编译器
    Apple苹果公司组织架构
    GPU与CPU交互技术
    CMOS图像传感器与DDI显示芯片
  • 原文地址:https://www.cnblogs.com/MrLJC/p/3672317.html
Copyright © 2020-2023  润新知