Half and Half 类型题
二分法的精髓在于判断目标值在前半区间还是后半区间,Half and Half类型难点在不能一次判断,可能需要一次以上的判断条件。
Maximum Number in Mountain Sequence
Given a mountain sequence of n
integers which increase firstly and then decrease, find the mountain top.
样例 Given
nums
= [1, 2, 4, 8, 6, 3]
return 8
Given nums
= [10, 9, 8, 7]
, return 10
public int mountainSequence(int[] nums) { // write your code here if(nums == null || nums.length == 0){ return -1; } int start = 0; int end = nums.length - 1; while(start + 1 < end){ int mid = start + (end - start)/2; if(nums[start] < nums[mid]){ if(nums[mid+1]<nums[mid]){ end = mid; } else{ start = mid; } } else{ if(nums[mid-1]<nums[mid]){ start = mid; } else{ end = mid; } } } if(nums[start] > nums[end]){ return nums[start]; } else{ return nums[end]; } //return -1; }
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。你可以假设数组中不存在重复的元素。
样例
给出[4, 5, 1, 2, 3]和target=1,返回 2
给出[4, 5, 1, 2, 3]和target=0,返回 -1
思路:判断目标值是否在某一区间/跨区间,再比较目标值
public int search(int[] A, int target) { // write your code here if(A == null | A.length == 0){ return -1; } int start = 0; int end = A.length - 1; while(start + 1 < end){ int mid = start + (end - start)/2; if (A[start] < A[mid]){ if(target >= A[start] && target <= A[mid]){ end = mid; } else{ start = mid; } } else{ if(target >= A[mid] && target <= A[end]){ start = mid; } else{ end = mid; } } } if(A[start] == target){ return start; } if(A[end] == target){ return end; } return -1; }