模拟,支付20元时优先找零10元和5元,再找零3个5元
class Solution:
def lemonadeChange(self, bills: List[int]):
five = 0
ten = 0
for i, bill in enumerate(bills):
if bill == 5:
five += 1
elif bill == 10:
if five == 0:
return False
five -= 1
ten += 1
elif bill == 20:
if ten >= 1 and five >=1:
five -= 1
ten -= 1
elif five >= 3:
five -= 3
else:
return False
return True
按照身高降序,按索引升序
class Solution:
def reconstructQueue(self, people: List[List[int]]):
people = sorted(people, key=lambda x: (-x[0], x[1]))
q = []
for p in people:
q.insert(p[1], p)
return q
贪心,按左端点排序,从左到右遍历,取右端点最小值。
class Solution {
public:
static bool cmp(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
int findMinArrowShots(vector<vector<int>>& points) {
int n = points.size();
if (n == 0) return 0;
sort(points.begin(), points.end(), cmp);
int ans = 1;
for (int i = 1; i < n; i++) {
if (points[i][0] > points[i - 1][1]) ans++;
else {
points[i][1] = min(points[i][1], points[i - 1][1]);
}
}
return ans;
}
};