LeetCode-Search in Rotated Sorted Array(在反转数组中的关键字)

题1:

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.

题2:如果数组有重复数字呢?


对于此题,可以先解决此题,找出反转数组中最小值。有了这题的基础,这题就简单了。

public int search(int[] A, int target) {
    	int low = 0;
        int high = A.length-1;
		while (low <= high) {
			int mid = low + (high - low) / 2;
			if (A[mid] == target) {
				return mid;
			} else if (A[mid] < A[high]) {//右侧有序
				if (A[mid] <= target && target <= A[high]) {
					low = mid+1;
				} else {
					high = mid-1;
				}
			} else {//左侧有序
				if (A[low] <= target && target <= A[mid]) {
					high = mid-1;
				} else {
					low = mid+1;
				}
			}
		}
        return -1;
    }
因为可以根据(low,mid)或(mid,high)有序,解决之。题2呢?

public boolean search(int[] A, int target) {
    	int low = 0;
        int high = A.length-1;
		while (low <= high) {
			int mid = low + (high - low) / 2;
			if (A[mid] == target) {
				return true;
			} else if (A[mid] < A[high]) {
				if (A[mid] <= target && target <= A[high]) {
					low = mid+1;
				} else {
					high = mid-1;
				}
			} else if (A[mid] > A[high]) {
				if (A[low] <= target && target <= A[mid]) {
					high = mid-1;
				} else {
					low = mid+1;
				}
			} else {
				high--;
			}
		}
        return false;
    }



你可能感兴趣的:(LeetCode-Search in Rotated Sorted Array(在反转数组中的关键字))