查找最小跳跃次数

finding minimum number of jumps

本文关键字:跳跃 查找      更新时间:2023-10-16

正在处理下面的算法难题,即找到最小跳跃次数。发布了详细的问题说明和两个代码版本来解决此问题。我做了测试,似乎两个版本都有效,我的第二个版本是第一版本代码的优化版本,这使我从i=maxIndex开始,而不是不断增加,这可以通过不迭代数组的所有插槽来节省时间。

我的问题是,想知道我的第二个版本代码是否100%正确?如果有人发现任何逻辑问题,请指出。

问题陈述

给定一个非负整数数组,您最初位于该数组的第一个索引处。

数组中的每个元素表示您在该位置的最大跳跃长度。

你的目标是以最少的跳跃次数达到最后一个指数。

例如:给定阵列A=[2,3,1,4]

到达最后一个索引的最小跳跃次数为2。(从索引0跳1步到1,然后跳3步到最后一个索引。)

第一版本代码

class Solution {
public:
    int jump(vector<int>& nums) {
        int i = 0, n = nums.size(), step = 0, end = 0, maxend = 0;
        while (end < n - 1) {
            step++;
            for (;i <= end; i++) {
                maxend = max(maxend, i + nums[i]);
                if (maxend >= n - 1) return step;
            }
            if(end == maxend) break;
            end = maxend;
        }
        return n == 1 ? 0 : -1;
    }
};

第二版本代码

class Solution {
public:
    int jump(vector<int>& nums) {
        int i = 0, n = nums.size(), step = 0, end = 0, maxend = 0;
        int maxIndex = 0;
        while (end < n - 1) {
            step++;
            for (i=maxIndex;i <= end; i++) {
                if ((i + nums[i]) > maxend)
                {
                  maxend = i + nums[i];
                  maxIndex = i;
                }
                if (maxend >= n - 1) return step;
            }
            if(end == maxend) break;
            end = maxend;
        }
        return n == 1 ? 0 : -1;
    }
};

提前感谢,Lin

最好的方法总是测试它。人类不能总是考虑特殊情况,但自动化测试可以覆盖大多数特殊情况。如果你认为你的第一个版本运行良好,你可以将第一个版本和第二个版本的结果进行比较。举个例子:

/*
 * arraySize    : array size to use for the test
 * min          : min jump in the array
 * max          : max jump in the array
 */
void testJumps(int arraySize, int min, int max){
    static int counter = 0;
    std::cout << "-----------Test " << counter << "------------" << std::endl;
    std::cout << "Array size : " << arraySize << "   Minimum Jump : " << min << "   Max Jump" << max << std::endl; 
    //Create vector with random numbers
    std::vector<int> vecNumbers(arraySize, 0);
    for(unsigned int i = 0; i < vecNumbers.size(); i++)
        vecNumbers[i] = rand() % max + min;
    //Value of first function
    int iVersion1 = jump1(vecNumbers);
    //Second fucntion
    int iVersion2 = jump2(vecNumbers);
    assert(iVersion1 == iVersion2);
    std::cout << "Test " << counter << " succeeded" << std::endl;
    std::cout << "-----------------------" << std::endl;
    counter++;
}
int main()
{
    //Two test
    testJumps(10, 1, 100);
    testJumps(20, 10, 200);
    //You can even make a loop of test
    //...
}