zoukankan      html  css  js  c++  java
  • 【Leetcode】Search in Rotated Sorted Array

    在旋转的无重复的排序数组中查找某个数,要求时间复杂度O(logN)

    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.

    思路:使用二分查找,若中间数大于等于最左端数,那左半部分必定有序,否则右半部分有序,通过将目标数与有序部分的最大与最小数比较就可以判断目标数位于哪一部分。代码如下:

    class Solution
    {
    public:
    	int search(int A[], int n, int target) 
    	{
    		return search(A,0,n-1,target);
    	}
    
    	int search(int *ary, int start, int end, int target)
    	{
    		if (start > end) return -1;
    
    		int mid = start + ((end-start)>>1);
    		int number0 = ary[start];
    		int number = ary[mid];
    		int number1 = ary[end];
    
    		if (number == target) 
    			return mid;
    
    		if (number >= number0)
    		{
    			if(target < number0 || target > number)
    				return search(ary,mid+1,end,target);
    			else
    				return search(ary,start,mid-1,target);
    		}
    		
    		// number < number0
    		if (target > number1 || target < number)
    			return search(ary,start,mid-1,target);
    		
    		return search(ary,mid+1,end,target);
    	}
    };


  • 相关阅读:
    概率的定义
    二项式分布与伯努利分布
    复数的表示方法
    <诗经>的由来
    王国维
    应该记住的历史事件
    switch条件变量的取值类型
    & 和 && 区别和联系,| 和 || 区别和联系
    成功安装 Visio 2016 和 Office 2016 的64位版本~~
    删除MicrosoftOffice2016的扫尾工作
  • 原文地址:https://www.cnblogs.com/james1207/p/3327644.html
Copyright © 2011-2022 走看看