題目:獲取一個正整數數組的最優跳動方式,要求如下:
1)從數組中間的任意位置開始向右跳,每次跳動的步伐數不能超過該位置對應元素的值
2)在跳動次數最少的情況下計算每次跳動的步伐
以下是實現,采用java實現~
package test; /** *為靜態工具類,具體功能見方法 * @author ZOUHENG */ public class MinStepToArrayEnd { /** * 根據當前位置的跳動范圍返回一個最優的位置,該位置使得連續兩次跳動可獲得最遠距離 如果當前位置可以直接跳出數組范圍,則最有位置為當前位置 * 這里默認傳入的參數已經經過驗證,滿足要求 * * @param target * 目標數組 * @param currentLocation * 當前位置,對應元素的從左到右的排列位置,第一個元素為1,最后一個元素為數組長度 * @return 最優秀位置 */ private static int getBestLocation(int[] target, int currentLocation) { // 初始化二連跳的最遠位置,可以超出數組范圍 int maxLocation = currentLocation + target[currentLocation - 1]; // 初始化當前位置 int bestLocation = currentLocation; // 遍歷當前位置覆蓋的元素,獲得二連跳的最遠位置和對應的最優位置 for (int i = 0; i <= target[currentLocation - 1]; i++) { int temp = target[(i + currentLocation) - 1] + (i + currentLocation); if (temp >= target.length) { return i + currentLocation; } if (temp > maxLocation) { maxLocation = temp; bestLocation = i + currentLocation; } } return bestLocation; } /** * 根據最佳位置與當前位置計算調動的步伐數量 * * @param target * @param currentLocation * @return */ private static int getJumpSteps(int[] target, int currentLocation) { int bestLocation = getBestLocation(target, currentLocation); // 如果最佳位置與當前位置相等,則說明可以直接從當前位置跳到末端,因此直接返回剩下的步伐 if (bestLocation == currentLocation) { return target.length - currentLocation; } // 如果不等,則返回最佳位置與當前位置的步伐差 return bestLocation - currentLocation; } /** * 獲取一個正整數數組的最優跳動方式,要求如下: * 從數組中間的任意位置開始向右跳,每次跳動的步伐數不能超過該位置對應元素的值 * 在跳動次數最少的情況下計算每次跳動的步伐 * * @param target * @param currentLocation * @return * @throws Exception * */ public static String getStepsResult(int[] target, int currentLocation) throws Exception { if (null == target || target.length == 0) throw new CheckParamException("數組參數為空或未初始化,請檢查······"); for (int i : target) if (i < 1) throw new CheckParamException("數組成員包含小於非正整數"); if (currentLocation < 1 || currentLocation > target.length) throw new CheckParamException("開始位置參數不正確,必須大於等於1並且小於等於" + target.length); String result = ""; int jumpSteps = getJumpSteps(target, currentLocation); while (jumpSteps + currentLocation != target.length) { result += jumpSteps + ","; currentLocation = getBestLocation(target, currentLocation); jumpSteps = getJumpSteps(target, currentLocation); } return result + jumpSteps; } /** * 測試 */ public static void main(String[] args) throws Exception { int a[] = { 4, 1, 5, 1, 3, 2, 1, 3, 1, 2, 3, 1, 1 }; System.out.println(getStepsResult(a, 1)); } /** * 自定義參數檢查異常 * * @author ZOUHENG */ private static class CheckParamException extends Exception { private static final long serialVersionUID = -5470930382435803070L; public CheckParamException(String message) { super(message); } } }