贪心 Part4
- 860.柠檬水找零
题目链接:. - 力扣(LeetCode)
思路:一定不要忽略找钱是有顺序的; 10块一定找 5 块,20 一定找 10+5或 5*3 组合,需要找钱的时候,一定要找 5 块
var lemonadeChange = function (bills) {
let five = 0, ten = 0, twenty = 0
for(let i = 0; i < bills.length; i = i + 1) {
if(bills[i] === 5) {
five = five + 1
}
if(bills[i] === 10) {
ten = ten + 1
five = five - 1
if(five < 0) return false
}
if(bills[i] === 20) {
five = five - 1
if(ten) {
ten = ten - 1
} else {
five = five - 2
if(five < 0)return false
}
}
}
return five > 0 ? true : false
};
const bills = [5,5,5,5,20,20,5,5,5,5]
console.log(lemonadeChange(bills))
- 406.根据身高重建队列
题目链接:https://leetcode.cn/problems/queue-reconstruction-by-height/
思路:k 表示前面有多少个人比当前高,那说明高的一定是排在前面的;
1) 先用 h 进行由高到低的排序; 这里如果有相等的,那则需要 k 大的在前面;
2)根据 k 的值来插入并生成新的数组,splice 会改变原数组
people.sort((a, b) => {
if(a[0] === b[0]) return a[1] - b[1]
return b[0] - a[0]
})
let queue = []
for(let k = 0; k < people.length; k = k + 1) {
queue.splice(people[k][1], 0, people[k])
}
return queue
- 452. 用最少数量的箭引爆气球
题目链接:力扣题目链接
思路: 首先对数组进行排序,判断出现重叠的数组的组合有多少个; 判断重叠是数组的开始和结尾都在当前判断数据第一个数据左右
实现代码:
points.sort((a, b) => a[0] - b[0])
let startPoint = points[points.length - 1], arrowNum = 1;
for(let i = points.length - 2; i >= 0; i = i -1) {
if(points[i][0] <= startPoint[0] && points[i][1] >= startPoint[0]) {
continue
}
startPoint = points[i]
arrowNum = arrowNum + 1
}
return arrowNum