zoukankan      html  css  js  c++  java
  • LeetCode Search in Rotated Sorted Array 在旋转了的数组中查找

    Search in Rotated Sorted Array 

    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.

    我突然想用英文解说下,展示一下我英文解说这么专业主题的功力O(∩_∩)O~,都搞双语的话好像又太费时间了。

    This is a classic interview question. It's solution is similar with normal binary search. The only difference is that we need to add more conditional sentences.

    和普通的二分法差不多

    The key points is when we divide the array into two half, we need to compare A[mid] with one of the end element of the array, so that we can know which half of the array is sorted, and which half is rotated, and divided them again subsequently.

    关键是会增加条件判断

    The difference I do here is that I add one normal binary search here as  a helper function. Actually you don't need the binary search function, just one function will be alright. But that's fun to add them together to check the difference between them.

    增加普通的binary search对比一下

    class Solution {
    public:
    	int search(int A[], int n, int target) 
    	{
    		return unordBiSearch(A, 0, n-1, target);
    	}
    
    	int unordBiSearch(int A[], int low, int up, int tar)
    	{
    		if (low > up) return -1;
    		
    		int mid = (low+up)>>1;
    		if (A[mid] == tar)
    			return mid;
    		if (A[mid]>A[up])
    		{
    			if (A[low] <= tar && A[mid] > tar)
    				return biSearch(A, low, mid-1, tar);
    			else return unordBiSearch(A, mid+1, up, tar);
    		}
    		if (A[mid]<A[up])
    		{
    			if (A[mid] < tar && A[up] >= tar)
    				return biSearch(A, mid+1, up, tar);
    			else return unordBiSearch(A, low, mid-1, tar);
    		}
    		return -1;
    	}
    
    	int biSearch(int A[], int low, int up, int key)
    	{
    		if(low>up) return -1;  
    		int mid = (low+up)>>1;  
    		if (key < A[mid])  
    			return biSearch(A, low, mid-1, key);  
    		else if (A[mid] < key)  
    			return biSearch(A, mid+1, up, key);  
    		return mid; 
    	}
    };


     

  • 相关阅读:
    Linux内核设计与实现 总结笔记(第五章)系统调用
    Linux内核设计与实现 总结笔记(第四章)进程调度
    Linux内核设计与实现 总结笔记(第三章)进程
    Linux内核设计与实现 总结笔记(第二章)
    4412 移植x264并且YUV422转x264
    4412 使用usb摄像头拍照YUYV格式
    LDD3 第15章 内存映射和DMA
    LDD3 第13章 USB驱动程序
    ldd3 第12章 PCI驱动程序
    4412 移植mpu9250尝试
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3454150.html
Copyright © 2011-2022 走看看