134. 加油站
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int curSum = 0;
int totalSum = 0;
int start = 0;
for(int i = 0;i < gas.length;i++){
curSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if(curSum < 0){
start = i + 1;
curSum = 0;
}
}
if(totalSum < 0)return -1;
else return start;
}
}
135. 分发糖果
本题涉及到一个思想,就是想处理好一边再处理另一边,不要两边想着一起兼顾,后面还会有题目用到这个思路
先从左往右遍历,右比左大就赋值2,其他赋值1
再从右往左遍历,左比右大就比右边的值多1,取最大值
class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int[] candy = new int[len];
candy[0] = 1;
//右比左大
for(int i = 1;i < len;i++){
if(ratings[i - 1] < ratings[i])candy[i] = candy[i - 1] + 1;
else candy[i] = 1;//漏了
}
//左比右大
for(int i = len - 1;i >= 1;i--){
if(ratings[i - 1] > ratings[i])candy[i - 1] = Math.max(candy[i] + 1,candy[i - 1]);
}
int sum = 0;
for(int c:candy){
sum += c;
}
return sum;
}
}
860.柠檬水找零
付20优先找10+5,然后找3*5
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0;
int ten = 0;
for(int i = 0;i < bills.length;i++){
if(bills[i] == 5){
five++;
}
if(bills[i] == 10){
five--;
if(five < 0)return false;
ten++;
}
if(bills[i] == 20){
if(ten >= 1){
ten--;
five--;
if(five < 0)return false;
}else{
five -= 3;
if(five < 0)return false;
}
}
}
return true;
}
}
406.根据身高重建队列
本题有点难度,和分发糖果类似,不要两头兼顾,处理好一边再处理另一边。

class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people,(a,b)->{
if(a[0] == b[0])return a[1] - b[1];
return b[0] - a[0];
});
LinkedList<int[]> que = new LinkedList<>();
for(int[] p:people){
que.add(p[1],p);//Linkedlist.add(index, value),會將value插入到指定index裡
}
return que.toArray(new int[que.size()][]);
}
}
874

被折叠的 条评论
为什么被折叠?



