数组-Search in Rotated Sorted Array(在一个旋转的数组中查找想要的值的指针)

来源:互联网 发布:黑客腾讯软件下载中心 编辑:程序博客网 时间:2024/05/18 01:22

问题描述:

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Subscribe to see which companies asked this question

在一个旋转的数组中查找想要的值的指针,没有则返回-1.

思考:

使用二分法,需找中点,既然是旋转数组,那么切入点就是递增和递减序列。

代码(java):

public class SearchInRotatedSortedArray {public int search(int[] nums, int target) {int left = 0, right = nums.length - 1;         while( left <= right){                          int mid = (left + right)/2;                          if(nums[mid] == target){                 return mid;             }                           ///考虑中点索引小于等于最大值索引             if(nums[left] < nums[mid]){                 //肯定在左边,左边一定是递增的                 if(target <= nums[mid] && target >= nums[left]){                     right = mid - 1;                 }                 //要么中点在最大值左边,要么中点是最大值                 else if(target > nums[mid] || target < nums[left]){                     left = mid + 1;                 }             }              //考虑中点索引大于等于最小值索引             else if (nums[left] > nums[mid]){                 //中点要么是最小值,要么在最小值的右边                 if(target >= nums[left] || target <= nums[mid]){                     right = mid -1;                 }                 //肯定在左边                 else if(target > nums[mid] || target < nums[right]){                 left = mid + 1;                 }             }             else left ++;         }         return -1;    }public static void main(String[] args){int[] nums = new int[]{4 ,5 ,6 , 7, 0, 1, 2};System.out.println(new SearchInRotatedSortedArray().search(nums, 4));}}




0 0
原创粉丝点击