搜索旋转排序数组
解题思路:二分查找+二分查找递增分界点
class Solution { public int search(int[] nums, int target) { int len = nums.length; if(len==0){ return -1; } if(len==1){ return nums[0]==target?0:-1; } int end = len - 2; int start = 0; int mid = 0; while(start<=end){ mid = (start+end)/2; if(nums[mid]>nums[mid+1]){ break; }else if(nums[mid]>=nums[start]){ start = mid + 1; }else{ end = mid - 1; } } if(start>end){ end = len - 1; }else{ end = mid; } if(target==nums[0]){ return 0; }else if(target<nums[0]){ start = end + 1; end = len - 1; }else{ start = 1; } while(start<=end){ mid = (start+end)/2; if(nums[mid]==target){ return mid; }else if(nums[mid]<target){ start = mid + 1; }else{ end = mid - 1; } } return -1; } }
第二种方法:
解题思路:二分法查找+多种情况
class Solution { public int search(int[] nums, int target) { int len = nums.length; if(len==0){ return -1; } int end = len - 1; int start = 1; int mid = 0; if(target==nums[0]){ return 0; } while(start<=end){ mid = (start+end)/2; if(nums[mid]==target){ return mid; }else if(nums[mid]>nums[0]){ if(target>nums[mid]){ start = mid + 1; }else if(target<nums[0]){ start = mid + 1; }else{ end = mid - 1; } }else{ if(target<nums[mid]){ end = mid - 1; }else if(target>nums[0]){ end = mid - 1; }else{ start = mid + 1; } } } return -1; } }
第三种方法:
解题思路:二分法查找+合并多种情况
class Solution { public int search(int[] nums, int target) { int len = nums.length; if(len==0){ return -1; } int end = len - 1; int start = 1; int mid = 0; if(target==nums[0]){ return 0; } while(start<=end){ mid = (start+end)/2; if(nums[mid]==target){ return mid; }else if((nums[mid]>nums[0])^(target>nums[mid])^(target>nums[0])){ start = mid + 1; }else{ end = mid - 1; } } return -1; } }