zoukankan      html  css  js  c++  java
  • [LeetCode] Jump Game 数组控制

    Given an array of non-negative integers, you are initially positioned at the first index of the array.

    Each element in the array represents your maximum jump length at that position.

    Determine if you are able to reach the last index.

    For example:
    A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.

    Hide Tags
     Array Greedy
     
     
     
     题目很简单,思路如下:
    1. 创建一个标记为last,表示A数组下标为last 前的位置都可以达到,初始化为 1.
    2. 从左遍历数组,当前位置加上可跳跃的长度A[i] 更新last。
    3. 如果last >= n ,即可以达到数组末尾,否则失败。

    我写的如下:

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6     bool canJump(int A[], int n) {
     7         if(n<=1)    return true;
     8         int last = 1;
     9         for(int i =0;i<last&&i<n;i++){
    10             last = last>i+A[i]+1?last:i+A[i]+1;
    11             if(last>=n) return true;
    12         }
    13         return false;
    14     }
    15 };
    16 
    17 int main()
    18 {
    19     int A[] = {3,2,1,0,4};
    20     Solution sol;
    21     cout<<sol.canJump(A,sizeof(A)/sizeof(int))<<endl;
    22     return 0;
    23 }
    View Code
     
     另外一个思路:
        从右到左遍历数组,如果遇到0,则判断该位置左边是否存在某位置可以跨越过该0,如果不能跨越了,则返回false。
     
     
     1 #include <iostream>
     2 using namespace std;
     3 
     4 /**class Solution {
     5 public:
     6     bool canJump(int A[], int n) {
     7         if(n<=1)    return true;
     8         int last = 1;
     9         for(int i =0;i<last&&i<n;i++){
    10             last = last>i+A[i]+1?last:i+A[i]+1;
    11             if(last>=n) return true;
    12         }
    13         return false;
    14     }
    15 };
    16 */
    17 class Solution {
    18 public:
    19     bool canJump(int A[], int n) {
    20         for(int i = n-2; i >= 0; i--){
    21             if(A[i] == 0){
    22                 int j;
    23                 for(j = i - 1; j >=0; j--){
    24                     if(A[j] > i - j)    break;
    25                 }
    26                 if(j == -1) return false;
    27             }
    28         }
    29         return true;
    30     }
    31 };
    32 
    33 int main()
    34 {
    35     int A[] = {3,2,1,1,4};
    36     Solution sol;
    37     cout<<sol.canJump(A,sizeof(A)/sizeof(int))<<endl;
    38     return 0;
    39 }
    View Code
     
     
     
     
     
     
     
  • 相关阅读:
    VTK初学一,b_PolyVertex多个图形点的绘制
    VTK初学一,a_Vertex图形点的绘制
    Python基础学习之集合
    Apache
    NTP时间同步服务和DNS服务
    NFS服务及DHCPD服务
    samba服务及vsftpd服务
    Linux rpm和yum软件管理
    Linux网络技术管理及进程管理
    Linux RAID磁盘阵列
  • 原文地址:https://www.cnblogs.com/Azhu/p/4127612.html
Copyright © 2011-2022 走看看