代码随想录算法训练营Day29
加油站
如果gassum小于0,那么起点一定在下一个位置
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalSum = 0;
int gasSum = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
totalSum += gas[i] - cost[i];
}
if (totalSum < 0) {
return -1;
}
for (int i = 0; i < gas.length; i++) {
gasSum += gas[i] - cost[i];
if (gasSum < 0) {
start = i + 1;
gasSum = 0;
}
}
return start;
}
}
分发糖果
从左往右和从右往左,取最大值
class Solution {
public int candy(int[] ratings) {
int totalCandies = 0;
int[] candies = new int[ratings.length];
Arrays.fill(candies, 1);
// 从左到右遍历,如果右边的孩子的评分高于左边的孩子,则右边孩子的糖果数比左边多 1 for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// 从右到左遍历,如果左边的孩子的评分高于右边的孩子,且左边的糖果数不大于右边的孩子,则左边孩子的糖果数更新为右边孩子的糖果数加 1 for (int i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
for (int candy : candies) {
totalCandies += candy;
}
return totalCandies;
}
}
柠檬水找零
这个简单,贪心只体现在20时优先找零10
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++;
}else if(bills[i] == 10){
five--;
ten++;
}else if(bills[i] == 20){
if(ten>0){
ten--;
five--;
}else{
five = five-3;
}
}
if(five<0){
return false;
}
}
return true;
}
}
根据身高重建队列
先按照h从高到低排,当h相同时,k从低到高排,依次插入,后面插入的下标刚好为k的值
class Solution {
public int[][] reconstructQueue(int[][] people) {
// 身高从大到小排(身高相同k小的站前面)
Arrays.sort(people, (a, b) -> {
if (a[0] == b[0]) return a[1] - b[1]; // a - b 是升序排列,故在a[0] == b[0]的狀況下,會根據k值升序排列
return b[0] - a[0]; //b - a 是降序排列,在a[0] != b[0],的狀況會根據h值降序排列
});
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[people.length][]);
}
}

浙公网安备 33010602011771号