33. Search in Rotated Sorted Array旋转数组二分法查询
一句话思路:反正只是寻找一个最小区间,断开也能二分。根据m第一次的落点,来分情况讨论。
一刷报错:
- 结构上有根本性错误:应该是while里面包括if,不然会把代码重复写两遍,不好。
//situation1 if (nums[mid] > nums[start]) { while (start + 1 < mid) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[start] <= target && target <= nums[mid]) { end = mid; } else start = mid; } } //situantion2 else { while (start + 1 < mid) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] <= target && target <= nums[end]) { start = mid; } else end = mid; } }
- int方法的corner case返回值:数组为空,数组长度为0
- 居然没有写target== nums[mid]的特殊情况,该死!
一句话总结思路:要把while放在外面,if放在里面。
二刷ac
public class Solution { /* * @param nums: an integer rotated sorted array * @param target: an integer to be searched * @return: an integer */ public int search(int[] nums, int target) { // write your code here if (nums.length == 0 || nums == null) { return -1; } int start = 0; int end = nums.length - 1; int mid; while (start + 1 < end) { mid = start + (end - start) / 2; //situation1,red line if (nums[mid] > nums[start]) { if (nums[mid] == target) { end = mid; } else if (nums[start] <= target && target <= nums[mid]) { end = mid; } else start = mid; } //situation2,green line else { if (nums[mid] == target) { end = mid; } if (nums[mid] <= target && target <= nums[end]) { start = mid; } else end = mid; } } if (nums[start] == target) { return start; } if (nums[end] == target) { return end; } return -1; } }