【leetcode】Array——Jump Game2(45)

題目:

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.)

思路:首先想到的就是BFS。一層一層遍歷,一旦reach末尾,返回遍歷的層數。然後用Queue實現BFS。算法結果沒問題,就是時間複雜度太高。

後來看了leetcode上面解法,優化了自己的BFS,時間複雜度也降到了O(n)。

記錄每一步能jump到的最遠距離nums[i]+i

舉個栗子:2 3 1 1 4

從2開始jump,能到到的最遠距離是2,經過元素3和1;然後計算第二跳,能到到達的最大距離:3+1=4 1+2=3,所以第二跳最遠距離是4,達到終點,所以返回2

代碼:

    public int jump(int[] nums) {
    	int currentMax=0;
    	int nextMax=0;
    	int step=0;
    	int i=0;
    	while(i<=nums.length-1){
    		currentMax=nextMax;
    		if(nextMax>=nums.length-1)
	    		return step;
	    	while(i<=currentMax){
	    		nextMax=Math.max(nextMax, nums[i]+i);
	    		i++;
	    	}
	    	step++;
    	}
    	return 0;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章