leetcode--JumpGame
2015-07-01 13:10
441 查看
思路:
贪心算法,利用局部最优解达到全局最优解。在每个节点拓展能达到的最远距离,如果当前节点能达到的最远距离等于当前节点那么就无法继续前进,返回false。如果当前节点能达到的最远距离大于等于末尾节点那么返回true。
/**
* Created by marsares on 15/7/1.
*/
public class JumpGame {
public boolean canJump(int[] nums) {
int max=0;
for(int i=0;i<nums.length;i++){
if(i+nums[i]>max)max=i+nums[i];
if(max>=nums.length-1)return true;
if(max==i)return false;
}
return true;
}
public static void main(String[]args){
JumpGame jg=new JumpGame();
int[]nums={0};
System.out.println(jg.canJump(nums));
}
}
贪心算法,利用局部最优解达到全局最优解。在每个节点拓展能达到的最远距离,如果当前节点能达到的最远距离等于当前节点那么就无法继续前进,返回false。如果当前节点能达到的最远距离大于等于末尾节点那么返回true。
/**
* Created by marsares on 15/7/1.
*/
public class JumpGame {
public boolean canJump(int[] nums) {
int max=0;
for(int i=0;i<nums.length;i++){
if(i+nums[i]>max)max=i+nums[i];
if(max>=nums.length-1)return true;
if(max==i)return false;
}
return true;
}
public static void main(String[]args){
JumpGame jg=new JumpGame();
int[]nums={0};
System.out.println(jg.canJump(nums));
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)