Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
You may assume no duplicate exists in the array.
思路:此題算法上不難,第一步計算旋轉的步長。然後根據步長分情況得到升序的新的數組。然後二分查找target的索引,找到後再分情況返回元素的位置。
具體代碼如下:
public class Solution { public int search(int[] nums, int target) { if(nums.length == 0){ return -1; } if(nums.length == 1){ if(nums[0] == target) return 0; return -1; } int rotate = 0;//旋轉的步長 for(int i = nums.length - 1; i > 0; i--){ if(nums[i] < nums[i-1]){ rotate = i; break; } } int[] a = new int[nums.length]; //將數組按升序填充到新數組 for(int i = rotate; i < nums.length; i++){ a[i - rotate] = nums[i];//後面未旋轉部分 } for(int i = 0; i < rotate; i++){ a[i+nums.length-rotate] = nums[i];//前面旋轉部分 } int index = -1; //二分查找 int low = 0; int hight = nums.length - 1; while(low <= hight){ int mid = (low + hight)/2; if(a[mid] > target){ hight = mid - 1; }else if(a[mid] == target){ index = mid; break; }else{ low = mid + 1; } } if(index == -1) return -1; if(index + rotate > nums.length - 1) return index + rotate - nums.length; return index + rotate; } }