• 【Leetcode】Search in Rotated Sorted Array II


    从一个旋转的排序数组中寻找一个数字,数组中可能有重复数字,要求时间复杂度O(LogN)。

    ( 1 1 1 2 4  might become 1 1 2 4 1).

    You are given a target value to search. If found in the array return true, otherwise return false.

    思路:二分查找,需要注意的是,若中间数字跟最左端数字相等时,去掉最左端的数字,然后递归查找。代码如下:

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



  • 相关阅读:
    Redis常见数据类型
    MYSQL常见可优化场景
    算术切片
    找数组里没出现的数
    不同路径和(II)
    不同路径和
    最小路径和
    强盗抢房子
    丑数(2)
    判断子序列
  • 原文地址:https://www.cnblogs.com/james1207/p/3327603.html
Copyright © 2020-2023  润新知