标签:time medium exists code tag hal highlight cat class
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. Have you met this question in a real interview? Yes Example For [4, 5, 1, 2, 3] and target=1, return 2. For [4, 5, 1, 2, 3] and target=0, return -1. Challenge O(logN) time Tags Sorted Array Array LinkedIn Binary Search Uber Facebook Related Problems Medium Search in Rotated Sorted Array II 40 % Easy Search a 2D Matrix
有序数组的题, 二分法, 根据mid的位置再确定start 和end的位置, 画图分情况
public int search(int[] A, int target) { // write your code here if (/*A == null ||*/ A.length == 0){ return -1; } int start = 0, end = A.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (A[mid] == target) { return mid; } if (A[start] < A[mid] && A[start] > A[end]){ if (A[mid] > target && A[start] <= target) { end = mid; } else { start = mid; } } else if (A[start] <= A[mid] && A[mid] <= A[end]) { if (A[mid] < target) { start = mid; } else { end = mid; } } else { if (A[mid] < target && target <= A[end]) { start = mid; } else { end = mid; } } } if (A[start] == target) { return start; } else if (A[end] == target) { return end; } else { return -1; } }
Search in Rotated Sorted Array
标签:time medium exists code tag hal highlight cat class
原文地址:http://www.cnblogs.com/apanda009/p/7262292.html