leetcode-zgd-day32-122.买卖股票的最佳时机II/55.跳跃游戏/45.跳跃游戏II

86 阅读1分钟

122.买卖股票的最佳时机II

题目链接:122. 买卖股票的最佳时机 II - 力扣(LeetCode)

解题思路:

贪心贪的是什么: 贪的是所以的正利润。只要是正利润就保留,算进和中。因为同一天可以卖出和买入

 class Solution {
     public int maxProfit(int[] prices) {
         int ans = 0;
         for(int i = 0; i < prices.length - 1; i++){
             ans += Math.max(0, prices[i + 1] - prices[i]);
         }
         return ans;
     }
 }

55.跳跃游戏

题目链接:Loading Question... - 力扣(LeetCode)

解题思路:

贪心贪的是什么: 贪的是能够跳跃到的最远距离。

 class Solution {
     public boolean canJump(int[] nums) {
         int cango = nums[0];
         for(int i = 0; i <= cango; i++){
             cango = Math.max(cango, i + nums[i]);
             if(i == nums.length - 1) return true;
         }
         return false;
     }
 }

45.跳跃游戏II

题目链接:45. 跳跃游戏 II - 力扣(LeetCode)

解题思路:

贪心贪的是什么:贪的是当前的距离最少需要跳多少步。贪的还是能够跳的最远距离,只不过会根据这个最远距离进行步数的计算。

 class Solution {
     public int jump(int[] nums) {
         if(nums.length == 1) return 0; // 特殊情况只有一个点。
         int ans = 0; // 次数
         int cango = nums[0]; // 记录每一步能到的最远距离
         int newgo = 0;
         for(int i = 0; i < nums.length; i++){ //一定能够到达终点,所以遍历整个nums数组即可
             // i + nums[i] 当前结点能到的最远距离, newgo,当前步数所能到达的最远距离,最后将其赋值给cango
             newgo = Math.max(newgo, i + nums[i]);
             if(i == nums.length - 1) return ans + 1; // 到达最后一个点的时候,ans+1直接返回。+1是因为最后一步还没加
             if(i == cango){ // 当前步数能够到达的最远距离就是这了,再往后需要额外增加步数。
                 ans++;
                 cango = newgo;
             }
         }
         return -1;
     }
 }

感觉当前这个解题思路并不是足够清晰,写代码解释的时候也是有点糊涂

官方版本一代码:

 class Solution {
     public int jump(int[] nums) {
         if (nums == null || nums.length == 0 || nums.length == 1) {
             return 0;
         }
         //记录跳跃的次数
         int count=0;
         //当前的覆盖最大区域
         int curDistance = 0;
         //最大的覆盖区域
         int maxDistance = 0;
         for (int i = 0; i < nums.length; i++) {
             //在可覆盖区域内更新最大的覆盖区域
             maxDistance = Math.max(maxDistance,i+nums[i]);
             //说明当前一步,再跳一步就到达了末尾
             if (maxDistance>=nums.length-1){
                 count++;
                 break;
             }
             //走到当前覆盖的最大区域时,更新下一步可达的最大区域
             if (i==curDistance){
                 curDistance = maxDistance;
                 count++;
             }
         }
         return count;
     }
 }

官方版本二代码:

 class Solution {
     public int jump(int[] nums) {
         int result = 0;
         // 当前覆盖的最远距离下标
         int end = 0;
         // 下一步覆盖的最远距离下标
         int temp = 0;
         for (int i = 0; i <= end && end < nums.length - 1; ++i) {
             temp = Math.max(temp, i + nums[i]);
             // 可达位置的改变次数就是跳跃次数
             if (i == end) {
                 end = temp;
                 result++;
             }
         }
         return result;
     }
 }