JavaSE8基礎 經典二分查找問題 折半查找
阿新 • • 發佈:2017-09-13
技術分享 sorted while int end num pos div ret 折半查找
question:
code:
public class Solution { /** * @param nums: An integer array sorted in ascending order * @param target: An integer * @return an integer */ public int findPosition(int[] nums, int target) { // Write your code here int start = 0; int end = nums.length - 1; int mid = 0; while(start <= end) { mid = (start + end) / 2; if(target < nums[mid]) { end = mid - 1; } else if(target > nums[mid]) { start = mid + 1; } else { return mid; } } return -1; } }
result:
JavaSE8基礎 經典二分查找問題 折半查找