33. Search in Rotated Sorted Array
虽然是hard难度,其实也没有很难
分为三种情况:
1. 如果nums[mid] == target
那么返回mid
2. 如果nums[mid] < nums[right]
那么说明在nums里面,从mid到right的顺序是正确的,所以:
1)如果target值范围介于nums[mid]和nums[right]之间
那么结果就在mid的右侧,所以left = mid+1;
2)否则right = mid-1
3.否则(也就是nums[mid]>= nums[right],就说明从left到mid的顺序是对的)
1)如果target值在left到mid中间
那么,right = mid-1;
2) 否则,left = mid+1
1 public int search(int[] nums, int target) { 2 if(nums == null || nums.length == 0) { 3 return -1; 4 } 5 int left = 0; 6 int right = nums.length-1; 7 while(left <= right) { 8 int mid = left+(right-left)/2; 9 if(nums[mid] == target) { 10 return mid; 11 } else if(nums[mid] < nums[right]) { 12 if(target > nums[mid] && target <= nums[right]) { 13 left = mid + 1; 14 } else { 15 right = mid - 1; 16 } 17 } else { 18 if(target < nums[mid] && target >= nums[left]) { 19 right = mid-1; 20 } else { 21 left = mid+1; 22 } 23 } 24 } 25 return -1; 26 }
bug记录
12行和18行,<=和>=,不能漏掉=,否则在边界上的数字就会被忽略,导致错误结果