【LeetCode】 58 搜索旋轉數組

題目:

image-20200716002556162

image-20200716002540628

解題思路:

二分法java

代碼:

package com.janeroad;

/**
 * Created on 2020/7/15.
 *
 * [@author](https://my.oschina.net/arthor) LJN
 */
public class Test21 {
    public int search(int[] arr, int target) {
        int l = 0;
        int h = arr.length - 1;
        while (l <= h) {
            int mid = l + (h - l >> 1);
            if (arr[mid] >= target) {
                if (arr[h] < arr[mid] && arr[h] >= target) {
                    l = mid + 1;
                } else {
                    h = mid - 1;
                }
            } else {
                if (arr[mid] < arr[l] && target >= arr[l]) {
                    h = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
        }
        if (l < arr.length && arr[l] == target) return l;
        return -1;

    }

    public static void main(String[] args) {
     Test21 test21 = new Test21();
     int[] arr=new int[]{15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14};
        int search = test21.search(arr, 4);
        System.out.println(search);
    }
}
相關文章
相關標籤/搜索