|
| 1 | +package com.blankj.medium._033; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by dash wang on 2/11/18. |
| 5 | + */ |
| 6 | +public class Solution2 { |
| 7 | + |
| 8 | + private int findDivisionIndex(int[] nums, int len) { |
| 9 | + int left = 0, right = 1; |
| 10 | + while (right < len && nums[left] < nums[right]) { |
| 11 | + left++; |
| 12 | + right++; |
| 13 | + } |
| 14 | + return left; |
| 15 | + } |
| 16 | + |
| 17 | + private int binarySearchRecursive(int[] nums, int low, int high, int target) { |
| 18 | + int foundIndex = -1; |
| 19 | + while (low < high) { |
| 20 | + int mid = (low + high) / 2; |
| 21 | + if (nums[mid] == target) { |
| 22 | + return mid; |
| 23 | + } else if (nums[mid] > target) { |
| 24 | + return binarySearchRecursive(nums, low, mid - 1, target); |
| 25 | + } else { |
| 26 | + return binarySearchRecursive(nums, mid + 1, high, target); |
| 27 | + } |
| 28 | + } |
| 29 | + return foundIndex; |
| 30 | + } |
| 31 | + |
| 32 | + private int binarySearchIteration(int[] nums, int low, int high, int target) { |
| 33 | + int foundIndex = -1; |
| 34 | + while(low < high) { |
| 35 | + int mid = (low + high) / 2; |
| 36 | + if(nums[mid] == target) { |
| 37 | + return mid; |
| 38 | + } else if(nums[mid] > target) { |
| 39 | + high = mid - 1; |
| 40 | + } else { |
| 41 | + low = mid + 1; |
| 42 | + } |
| 43 | + } |
| 44 | + return foundIndex; |
| 45 | + } |
| 46 | + |
| 47 | + public int search(int[] nums, int target) { |
| 48 | + int index = -1; |
| 49 | + int len = nums.length; |
| 50 | + // Find division index |
| 51 | + int divisionIndex = findDivisionIndex(nums, len); |
| 52 | + // Decide which side to search |
| 53 | + if (nums[0] <= target && nums[divisionIndex] >= target) { |
| 54 | + index = binarySearchIteration(nums, 0, divisionIndex, target); |
| 55 | + } else if (nums[divisionIndex + 1] <= target && nums[len - 1] >= target) { |
| 56 | + index = binarySearchIteration(nums, divisionIndex + 1, len, target); |
| 57 | + } |
| 58 | + return index; |
| 59 | + } |
| 60 | + |
| 61 | + public static void main(String[] args) { |
| 62 | + Solution2 solution2 = new Solution2(); |
| 63 | + System.out.println(solution2.search(new int[]{2, 1}, 1)); |
| 64 | + } |
| 65 | +} |
0 commit comments