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 }
原文地址:https://www.cnblogs.com/Juntaran/p/5511669.html