intcandy(vector<int> children){int num = children.size();if(num<2){return num;}
vector<int>candy(num,1);for(int i =1; i < num;i++){//从左向右扫描if(children[i]>children[i-1])
candy[i]= candy[i -1]+1;}for(int i = num -1; i >0;i--){//从右向左扫描if(children[i]< children[i-1])
candy[i-1]=max(candy[i]+1, candy[i -1]);}//accumulate可以很方便的求和returnaccumulate(candy.begin(), candy.end(),0);}
Non-overlapping Intervals(435)
题目描述
给定多个区间,计算让这些区间互不重叠所需要移除区间的最少个数,起止相连不算重叠
输入输出样例
Input:[[1,2],[2,4],[1,3]]
Output:1
解题思路
尽可能保留互不重叠的区间,首先按照区间结尾排序,然后移除冲突区间即可
参考代码
intnon_overlappingIntervals(vector<vector<int>> intervals){if(intervals.empty()){return0;}int n = intervals.size();sort(intervals.begin(), intervals.end(),[](vector<int>&a, vector<int>&b){return a[1]< b[1];});int removed =0, prev = intervals[0][1];for(int i =1; i < n; i++){if(intervals[i][0]<prev){++removed;}else{
prev = intervals[i][1];}}return removed;}