LeetCode_Candy
来源:互联网 发布:淘宝网 文胸故事模特 编辑:程序博客网 时间:2024/04/29 18:05
class Solution {public: //int candy(vector<int> &ratings) { // int result=0; // if (ratings.empty()) // { // return result; // } // // //常规思路:从左向右扫描ratings数组, // //用candys[i]记录第i各小孩所获得的礼物数 // //记录最近的递减子序列的起始位置startAdPos // //很据当前rating[i]与rating[i-1]之间的关系,调整递减子序列 // //当递减子序列中的最大礼物值超过candys[startAdPos]时,同样也对candys[starAdPos]进行调整 // //空间复杂度是O(n),时间复杂度O(n2) // int len=ratings.size(); // int *candys=new int[len]; // //分配candy // candys[0]=1; // int startAdPos=0;//记录要开始调整的位置 // for (int i=1;i<len;i++) // { // if (ratings[i]>ratings[i-1]) // { // candys[i]=candys[i-1]+1; // startAdPos=i; // } // else // { // /* if (ratings[i]==ratings[i-1]) // { // candys[i]=candys[i-1]; // }*/ // if (ratings[i]==ratings[i-1]) // { // startAdPos=i; // } // //调整之前的小孩礼物数量 // if (candys[i-1]==1) // { // for (int j=startAdPos+1;j<i;j++) // { // candys[j]=candys[j]+1; // } // if (candys[startAdPos+1]==candys[startAdPos]) // { // candys[startAdPos]++; // } // } // candys[i]=1; // } // } // // for (int i=0;i<len;i++) // { // cout<<candys[i]<<endl; // result+=candys[i]; // } // delete[] candys; // return result; //} int candy(vector<int> &ratings) { int result=0; if (ratings.empty()) { return result; } /*********************************************************************************************** **改进思路(Discuss中的最优解法): **主要思想同样是记录当前最近扫描的递减子序列; **不同的地方在于: **考虑最近递减ratings子序列人...r[k-1]<r[k]>r[k+1]>r[k+2]>....>r[k+p]<r[k+p+1] **则可以知道当前递减子序列中的孩子受到礼物最多的是r[k],记为pres **题目要求求出少的礼物发放数量,则有r[k+p]对应的礼物数1,故而 **r[k+1].....r[k+p]构成一个从p...1的递减序列 **算法中对r[k+1].....r[k+p]的计算方法做了优化,只记录递减子序列的长度即可 *************************************************************************************************/ int decreSeqLen=0;//ratings递减子序列长度 int prevs=1;//递减子序列前的 int maxInSeq=1; //ratings递减序列允许出现的candy最大值 result=1; vector <int>::iterator iter=ratings.begin()+1; for (;iter<ratings.end();iter++) { //r[k]<r[k+1] if (*iter>*(iter-1)) { prevs++; result+=prevs; decreSeqLen=0; maxInSeq=prevs; } else { if (*iter==*(iter-1)) { result+=1; decreSeqLen=0; maxInSeq=1; prevs=1; } else { //now in the decreSeq decreSeqLen++; result+=decreSeqLen; if (maxInSeq==decreSeqLen) { result++; maxInSeq++; } prevs=1; } } } return result; }};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?
0 0
- Leetcode_candy
- LeetCode_Candy
- leetcode_Candy
- leetCode_Candy
- HDU 2879 HeHe(经典积性函数)
- LeetCode_Single Number&Single NumberII
- unix环境编程 目录操作
- JS中的onload与jQuery中的ready区别
- 预处理调试标记
- LeetCode_Candy
- QT中的进程和线程
- SELinux简单学习
- SVM入门(七)为何需要核函数
- c# ListView清空
- Spring配置 <context:component-scan/> <mvc:annotation-driven />
- 线性表
- Hadoop2.4编译 伪分布安装 集群安装笔记
- 同一个tomcat开多个端口分别发布不同项目