Fastest algorithm to hop through an array

后端 未结 10 1291
栀梦
栀梦 2021-02-05 16:52

Start with an array A of positive numbers. Start at index 0. From index i, you can move to index i+x for any x <= A[i]. The goal is to find the minimum number of moves needed

10条回答
  •  星月不相逢
    2021-02-05 17:29

    My method: Create an array reqSteps to store the number of moves an input takes to escape.
    Start from the end of the array.
    Check if input[i] can escape the array by itself, if yes enter 1 in minSteps, if no, store the minimum of successive input[i] values + 1. Result is minSteps[0];
    The top method does not work for the input{ 10, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1 };
    It will give 9 as the answer.
    Correct answer is 2.

    public static void arrayHop()
    {
            int[] input = { 10, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1 };
            int length = input.length;
            int answer = calcArrayHop(input, length);
    
    }
    
    public static int calcArrayHop(int[] input, int length) {
        int minSteps;
        int[] reqSteps = new int[length];
        for(int i=0;i= 0; i--) {
            int minsteps = Integer.MAX_VALUE;
            if (i + input[i] >= length) {
                reqSteps[i] = 1;
            } else
            {
                for (int j = i+1; j <= (i + input[i]); j++) {
                    if(j>input.length-1)
                        break;
                    if (reqSteps[j] < minsteps)
                        minsteps = reqSteps[j];
                }
            reqSteps[i] = minsteps+1;
            }
    
    
        }
    
        return reqSteps[0];
    }
    

    }

提交回复
热议问题