力扣竞赛233场题解(三)

力扣竞赛233场题解(三)

第一题:

题意:

根据一个不定长数组,输出 严格升数组的最大数字和。

题解:

用最后结果sum和最后的最大值进行比较,并用? : 语句进行循环内部的处理,书写更加简洁。

代码:

 1 class Solution {
 2 public:
 3     int maxAscendingSum(vector<int>& nums) {
 4         int ans=0;
 5         int sum=0;
 6         for(int i=0;i<nums.size();i++)
 7         {
 8             sum = (i!=0 && nums[i]>nums[i-1]) ? sum+nums[i] : nums[i];
 9             ans=max(ans,sum);
10 11         }
12         return ans;
13         
14     }
15 };

 

第二题:

题目:https://leetcode-cn.com/problems/number-of-orders-in-the-backlog/

题意:

求积压订单中的订单总数。

题解:

优先队列,不断维护队列。默认是大根堆;取反是小根堆。

代码:

 1 typedef pair<int,int> PII;
 2  3 class Solution {
 4 public:
 5     int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
 6         priority_queue<PII> buy,sell;
 7         int mod =1e9+7;
 8         long long ans = 0 ;
 9 10         //当buy>=sell,匹配的时候
11         for(auto &i : orders)
12         {
13             if(i[2]==0)  //优先队列默认大根堆,数字从大到小输出的。
14             {
15                 buy.push({i[0],i[1]});
16             }
17             else
18             {
19                 sell.push({-i[0],i[1]});
20             }
21             ans += i[1];
22             while(!buy.empty())
23             {
24                 if(sell.empty() || -sell.top().first > buy.top().first)
25                 {
26                     break;
27                 }
28                 PII x = buy.top();
29                 buy.pop();
30                 PII y = sell.top();
31                 sell.pop();
32                 //匹配成功
33                 int cha = min(x.second,y.second);
34                 x.second -=cha;
35                 y.second -=cha;
36                 ans -= 2*cha;
37                 if(x.second)
38                 {
39                     buy.push(x);
40                 }
41                 else
42                 {
43                     sell.push(y);
44                 }
45             }
46             
47         }return ans% mod;
48     }
49 };

注意:queue和优先队列的区别。

        queue<int> q1;
      q1.push(2);
      q1.front() = 3;


      priority_queue<int> q2;
      q2.push(2);
      q2.top() = 3;

因为cost value本身不能改变,但是可以复制给别人。

 

参看链接:https://leetcode-cn.com/problems/number-of-orders-in-the-backlog/solution/c-you-xian-dui-lie-by-raymond_yp-7p1k/

大根堆、小根堆和优先队列的实现:https://blog.csdn.net/weixin_45697774/article/details/104481087

 

 

雪儿言
原文地址:https://www.cnblogs.com/weixq351/p/14920663.html