去哪网面试题:二分查找的变形题目
目的是为了在O(logn)的时间复杂度下解决此问题,所以用二分查找。
1 package com.hb.leetcode; 2 3 4 /* 5 * Search in Rotated Sorted Array 6 * 7 * Suppose a sorted array is rotated at some pivot unknown to you beforehand. 8 * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 9 * You are given a target value to search. 10 * If found in the array return its index, otherwise return -1. 11 * You may assume no duplicate exists in the array. 12 * 13 */ 14 15 public class SearchInRotated { 16 17 public static int search(int[] A , int target){ 18 return rec( A , target , 0 , A.length -1 ); 19 } 20 21 public static int rec(int[] A , int target , int low , int high){ 22 if(low > high){ //没找到的情况 23 return -1 ; 24 } 25 26 int mid = low + (high - low) / 2 ; 27 28 if(A[mid] == target){ //找到了 29 return mid; 30 } 31 32 int res = rec(A , target , low , mid -1 ); //在左侧查找 33 34 if(res == -1 ){ //如果左侧没有找到,继续在右侧查找 35 res = rec(A , target , mid + 1 , high ); 36 } 37 38 39 return res; 40 } 41 42 public static void main(String[] args) { 43 int[] A = { 2, 3, 4, 5, 6, 0 ,1}; 44 System.out.println(search(A, 0)); 45 } 46 47 48 49 }