455.分发饼干
题目分析:结果是找出饼干尺寸满足胃口值的孩子的数量,所以有一个累加过程
// 时间复杂度:O(N*logN) 因为谷歌排序为快排,火狐为归并,都是O(N*logN)
var findContentChildren = function(g, s) {
const sortFunc = function(a,b){
return a-b
}
g.sort(sortFunc) // 对胃口值进行排序
s.sort(sortFunc) // 对饼干尺寸进行排序
// 遍历,找出饼干尺寸满足胃口值的孩子,定义变量累计孩子数量
let i = 0
s.forEach(n=>{
if(n>=g[i]){
i+=1
}
})
return i // 返回满足的孩子数量
}
122. 买卖股票的最佳时机 II
局部最优:见好就收,见差就不动,不做任何长远打算
题目分析:求的是最大利润,所以有一个累加过程,需要定义变量累计
/** 时间复杂度:O(n) for循环
* 空间复杂度:O(1) 没有线性增长,是常量
*/
var maxProfit = function(prices) {
let profit = 0
for(let i=1;i<prices.length; i+=1){
// 如果今天比昨天高,就昨天买,今天卖
if(prices[i]>prices[i-1]){
profit += prices[i]-prices[i-1] // 利润 = 卖出 - 买入
}
}
return profit
};