zoukankan      html  css  js  c++  java
  • LeetCode 45

    Jump Game II

    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.

    Your goal is to reach the last index in the minimum number of jumps.

    For example:
    Given array A = [2,3,1,1,4]

    The minimum number of jumps to reach the last index is 2.
    (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

     1 /*************************************************************************
     2     > File Name: LeetCode045.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: Tue 13 May 2016 14:47:33 PM CST
     6  ************************************************************************/
     7  
     8 /*************************************************************************
     9     
    10     Jump Game II
    11     
    12     Given an array of non-negative integers, 
    13     you are initially positioned at the first index of the array.
    14 
    15     Each element in the array represents your maximum jump length at that position.
    16 
    17     Your goal is to reach the last index in the minimum number of jumps.
    18 
    19     For example:
    20     Given array A = [2,3,1,1,4]
    21 
    22     The minimum number of jumps to reach the last index is 2. 
    23     (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
    24 
    25  ************************************************************************/
    26 
    27 #include <stdio.h>
    28 
    29 int jump(int* nums, int numsSize) 
    30 {
    31     if( numsSize <= 1 )
    32     {
    33         return 0;
    34     }
    35     
    36     int left = nums[0];
    37     int right = nums[0];
    38     int count = 1;
    39     int max = 0;
    40     
    41     int i;
    42     for( i=1; i<numsSize; i++ )
    43     {
    44         if( i > left )
    45         {
    46             left = right;
    47             count ++;
    48         }
    49         right = (i+nums[i])>right ? (i+nums[i]) : right;
    50         if( left >= numsSize-1 )
    51         {
    52             return count;
    53         }
    54     }
    55     return 0;
    56 }
    57 
    58 int main()
    59 {
    60     int nums[] = {2,3,1,1,4};
    61     int numsSize = 5;
    62     
    63     int ret = jump( nums, numsSize );
    64     printf("%d
    ", ret);
    65     
    66     return 0;
    67 }
  • 相关阅读:
    14、Cahin of Responsibility 责任链 COR设计模式
    13、Visitor 访问者模式 访问数据结构并处理数据 行为型设计模式
    HTML inline 与block元素
    javascript 继承实现
    深入理解linux的权限设置和SUID,SGID以及粘滞位
    设置express ejs模板的后缀名html
    Centos 安装编译codeblocks&&codelite
    JavaScript中两种类型的全局对象/函数【转】
    Canvas vs. SVG[转]
    centos 学习总结
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5511669.html
Copyright © 2011-2022 走看看