Golden programmer interview - face questions rotation 10.03 search array (binary search)

1. Topic

Search rotating array. After a given array to sort, containing n integers, but the array has been rotated many times, the number is unknown.
Please write code to identify an element in the array, the array element is assumed that was originally arranged in ascending order. If a plurality of identical elements, returns the index value of the minimum one.

示例1:
 输入: arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 5
 输出: 8(元素5在该数组中的索引)
 
示例2:
 输入:arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 11
 输出:-1 (没有找到)
 
提示:
arr 长度范围在[1, 1000000]之间

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/search-rotate-array-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

A similar topic: LeetCode 81. The search rotation sorted array II (binary search)

class Solution {
public:
    int search(vector<int>& arr, int target) {
    	int l = 0, r = arr.size()-1, mid;
    	while(l < r)//无等号
    	{
    		mid = l+((r-l)>>1);
    		if(arr[l] == arr[mid])
    		{
    			if(arr[l] == target)
    				r = l;//上面while有等号,这里可能死循环
    			else
    				l++;
    		}
    		else if(arr[l] > arr[mid])//左边不是升序
    		{
    			if(arr[l] <= target || target <= arr[mid])
    				r = mid;
    			else
    				l = mid+1;
    		}
    		else if(arr[l] < arr[mid])//左边是升序
    		{
    			if(arr[l] <= target && target <= arr[mid])
    				r = mid;
    			else
    				l = mid+1;
    		}
    	}
    	return arr[l]==target ? l : -1;
    }
};

44 ms 12.4 MB

Published 806 original articles · won praise 1552 · Views 380,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105313146