1.跳跃游戏Ⅱ leetcode 45
class Solution {
public int jump(int[] nums) {
int cover = 0;
int maxConver = 0;
int res = 0;
for(int i=0;i<nums.length-1;i++){
cover = Math.max(cover,nums[i]+i);
if(i==maxConver){
res++;
maxConver = cover;
}
}
return res;
}
}
当index的位置超过了当前最大的覆盖范围,才会res++;而下一次的最大覆盖范围则是取决于上一次覆盖范围内可以跳到最远的位置。
2.加油站 leetcode 134
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int min = Integer.MAX_VALUE;
int[] ans = new int[gas.length];
for(int i=0;i<gas.length;i++){
ans[i] = gas[i]-cost[i];
sum+=ans[i];
if(sum<min){
min = sum;
}
}
if(sum<0){
return -1;
}
if(min>=0){
return 0;
}
for(int i=ans.length-1;i>0;i--){
min+=ans[i];
if(min>=0){
return i;
}
}
return -1;
}
}
计算剩余油量,当总的剩余油量小于0,不可能可以循环。从前向后累加油耗时,找最小总的油耗,当最小油耗>=0时,从0出发即可。否则就从后面往前遍历,找到可以使最小油耗和>=0的位置即可。
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalSum = 0;
int curSum = 0;
int res = 0;
for(int i=0;i<gas.length;i++){
curSum+=gas[i]-cost[i];
totalSum+=gas[i]-cost[i];
if(curSum<0){
curSum = 0;
res = i+1;
}
}
if(totalSum<0){
return -1;
}
return res;
}
}
位置[i,j]间的剩余油量为负数时,肯定不能从i-j里选择站点出发。从前往后遍历,找到剩余油量为正数的区间,区间起始位置就是汽车循环开始位置。
3.分发糖果 leetcode 135
class Solution {
public int candy(int[] ratings) {
int res = 0;
int[] candys = new int[ratings.length];
candys[0] = 1;
for(int i=1;i<ratings.length;i++){
if(ratings[i]>ratings[i-1]){
candys[i] = candys[i-1]+1;
}else{
candys[i] = 1;
}
}
for(int i = ratings.length-2;i>=0;i--){
if(ratings[i]>ratings[i+1]){
candys[i] = Math.max(candys[i+1]+1,candys[i]);
}
}
for(int i:candys){
res+=i;
}
return res;
}
}
4.柠檬水找零 leetcode 860
class Solution {
public boolean lemonadeChange(int[] bills) {
int count_5 = 0;
int count_10 = 0;
for(int i=0;i<bills.length;i++){
if(bills[i]==5){
count_5++;
}else if(bills[i]==10){
count_5--;
count_10++;
}else{
if(count_10>0){
count_10--;
count_5--;
}else{
count_5-=3;
}
}
if(count_5<0||count_10<0){
return false;
}
}
return true;
}
}
5.根据身高重建队列 leetcode 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];
});
List<int[]> res = new ArrayList<>();
for(int[] p:people){
res.add(p[1],p);
}
return res.toArray(new int[people.length][]);
}
}