今日任务
134. 加油站
135. 分发糖果
860.柠檬水找零
406.根据身高重建队列
134. 加油站
题目链接: . - 力扣(LeetCode)
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int totalSum = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
sum += gas[i] -cost[i];
totalSum += gas[i] -cost[i];
if (sum < 0) {
start = i + 1;
sum = 0;
}
}
if (totalSum < 0) return -1;
return start;
}
}
135. 分发糖果
题目链接: . - 力扣(LeetCode)
class Solution {
public int candy(int[] ratings) {
/*从左向右遍历,比较右边大于左边,如果大于,candy要加1*/
int[] candy = new int[ratings.length];
candy[0] = 1;
for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1]) {
candy[i] = candy[i - 1] + 1;
} else {
candy[i] = 1;
}
}
/*从右往左边遍历,比较右边大于左边*/
for (int i = candy.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candy[i] = Math.max(candy[i], candy[i + 1] + 1);
}
}
int res = 0;
for (int i = 0; i < candy.length; i++) {
res += candy[i];
}
return res;
}
}
860.柠檬水找零
题目链接: . - 力扣(LeetCode)
class Solution {
public boolean lemonadeChange(int[] bills) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(5,0);
map.put(10,0);
map.put(20,0);
for (int i = 0; i < bills.length; i++) {
map.put(bills[i], map.get(bills[i]) + 1);
if (bills[i] == 10) {
map.put(5, map.get(5) - 1);
}
if (bills[i] == 20){
if (map.get(10) > 0) {
map.put(10, map.get(10) - 1);
map.put(5, map.get(5) - 1);
} else {
map.put(5, map.get(5) - 3);
}
}
if (map.get(5) < 0 || map.get(10) < 0) {
return false;
}
}
return true;
}
}
406.根据身高重建队列
题目链接: . - 力扣(LeetCode)
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people,(o1,o2)-> {
if (o1[0] == o2[0]) return o1[1] - o2[1];
return o2[0] - o1[0];
});
LinkedList<int[]> list = new LinkedList<>();
for (int i = 0; i < people.length; i++) {
list.add(people[i][1], people[i]);
}
int[][] res = new int[people.length][2];
int index = 0;
for (int[] i: list) {
res[index++] = i;
}
return res;
}
}