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?

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

    这个题的意思还真不是很清楚,最开始我的理解是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 };
  • 相关阅读:
    算法与数据结构(二):队列
    算法与数据结构(二):链表
    算法与数据结构(一):时间复杂度与空间复杂度
    2018总结与2019规划
    VC++ IPv6的支持
    从项目中学习HTML+CSS
    xampp 中 mysql的相关配置
    yum卸载遇到的问题--待解决
    RHEL 6.5----heartbeat
    RHEL 6.5-----MFS
  • 原文地址:https://www.cnblogs.com/MrLJC/p/3672317.html
Copyright © 2011-2022 走看看