《数据结构和Java集合框架第三版》读书笔记(二)——二分法检索

一,在一个数组里搜索某个元素,最容易被想到的是顺序搜索,从头开始搜,直到搜到为止。

最坏情况运行时间和平均运行时间都和n成线性关系

 

二,二分法检索的递归算法:

要求数组已经进行了排序,一般按照升序

基本思想:假设数据是按升序排序的,对于给定值x,从序列的中间位置开始比较,如果当前位置值等于x,则查找成功;若x小于当前位置值,则在数列的前半段中查找;若x大于当前位置值则在数列的后半段中继续查找,直到找到为止。<http://zengzhaoshuai.iteye.com/blog/1130376>

 

 public static int binarySearch(Object[ ] a, Object key) 
    {
       // throw new UnsupportedOperationException(); 
       return binarySearch(a,0,a.length-1,key);
    } // method binarySearch

    private static int binarySearch(Object[] a, int first,int last,Object key) 
    {
       if(first<=last){
    	   int mid=(first+last)>>1;
       		Object midval=a[mid];
       		int comp=((Comparable)midval).compareTo(key);
       		if(comp>0)
       			return binarySearch(a,first,mid-1,key);
       		else if(comp==0)
       			return mid;
       		else
       			return binarySearch(a,mid+1,last,key);
       }
       return -first-1;
    } // method binarySearch


 

成功和不成功搜索的最坏情况运行时间和平均运行时间均和n成对数关系

 

三,二分法检索的迭代算法

intfirst = 0;

intlast = a.length - 1;

 

递归算法里的if(first<=last)改成while(first<=last)

 

//针对int类型数组的二分法查找,key为要查找数的下标
	private static int binarySearch0(int[] a, int fromIndex, int toIndex,
				     int key) {
	int low = fromIndex;
	int high = toIndex - 1;
	while (low <= high) {
	    int mid = (low + high) >>> 1;
	    int midVal = a[mid];

	    if (midVal < key)
		low = mid + 1;
	    else if (midVal > key)
		high = mid - 1;
	    else
		return mid; // key found
	}
	return -(low + 1);  // key not found.
    }


四,leetcode上的一系列二分查找的题目

http://oj.leetcode.com/problems/sqrtx/

http://oj.leetcode.com/problems/search-in-rotated-sorted-array/
http://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/

https://leetcode.com/problems/median-of-two-sorted-arrays/

第一题:

Implement int sqrt(int x).

Compute and return the square root of x.

解法一:二分法

class Solution {
    public int sqrt(int x) {
      if(x == 0) return 0;
      if(x==1) return 1;
      int start=1, end=x,mid=0;
      while(start+1<end){
          mid = (start+end)>>>1;
          if(mid > x/mid)
              end = mid;
          else if(mid < x/mid)
              start = mid;
          else
              return mid;
      }
      return start;
    }
};

解法二:牛顿迭代法

转载自http://blog.csdn.net/doc_sgl/article/details/12404971


   为了方便理解,就先以本题为例:

   计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示。

   首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1

   同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2

   以此类推。

   以这样的方式得到的xi会无限趋近于f(x)=0的解。

   判断xi是否是f(x)=0的解有两种方法:

   一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。

 

经过(xi, f(xi))这个点的切线方程为f(x) = f(xi) + f’(xi)(x - xi),其中f'(x)为f(x)的导数,本题中为2x。令切线方程等于0,即可求出xi+1=xi - f(xi) / f'(xi)。

继续化简,xi+1=xi - (xi- n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。

有了迭代公式xi+1= (xi + n/xi) / 2,程序就好写了。关于牛顿迭代法,可以参考wikipedia以及百度百科

public class Solution {
    public int sqrt(int x) { 
        if (x ==0) return 0;  
        double pre;  
        double cur=1;  
        do  
        {  
            pre = cur;  
            cur = x / (2 * pre) + pre / 2.0;  
        } while (Math.abs(cur - pre) > 0.00001);  
        return (int)cur;  
    }
}


第二题:

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.

public class Solution {
    public int search(int[] A, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int start = 0;
        int end = A.length-1;

       
        while(start<=end){
            int mid =(start+end)>>1;
            if(target==A[mid])
                return mid;
            if(target == A[start])
                return start;
            if(target == A[end])
                return end;
            if(A[mid]>A[start]){                
                 if(target>A[start] && target<A[mid])
                    end = mid -1;
                else
                    start = mid + 1;
            }else{                              
               if(target>A[mid] && target<A[end])
                    start = mid+1;
                else
                    end = mid-1;
            }
        }
        return -1;
    }
}

第三题:

Search in Rotated Sorted Array II

 

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


 
public class Solution {
    public boolean search(int[] A, int target) {
        if(A==null) throw new IllegalArgumentException();
        int start=0,end=A.length-1,mid;
        while(start<=end){
            mid =(end+start)>>1;
            if(target==A[mid]||target == A[start]||target == A[end])
                return true;
             if(A[mid]>A[start]){//mid在左数组,分界线在mid右边                
                 if(target>A[start] && target<A[mid])
                    end = mid -1;
                else
                    start = mid + 1;
            }else if(A[mid]<A[start]){  //mid在右数组,分界线在mid左边                               
               if(target>A[mid] && target<A[end])
                    start = mid+1;
                else
                    end = mid-1;
            }
            else{
                start++;
            }
        }
        return false;
    }
}

第四题

 Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

解答:

https://discuss.leetcode.com/topic/4996/share-my-o-log-min-m-n-solution-with-explanation/15

<pre name="code" class="java">public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m=nums1.length,n=nums2.length;
        if(m>n){
            return findMedianSortedArrays(nums2,nums1);
        }
        int i=0,j=0,imin=0,imax=m,half=(m+n+1)>>1;
        int maxLeft=0,minRight=0;
        while(imin<=imax){
            i=(imin+imax)>>1;
            j=half-i;
            if(i>0&&j<n&&nums1[i-1]>nums2[j]){
                imax=i-1;
            }else if(j>0&&i<m&&nums2[j-1]>nums1[i]){
                imin=i+1;
            }else{
                if(i==0) maxLeft=nums2[j-1];
                else if(j==0) maxLeft=nums1[i-1];
                else maxLeft=getMax(nums1[i-1],nums2[j-1]);
                break;
            }
        }
        //如果m+n为奇数,取中间值
        if(((m+n)&1)!=0) return maxLeft;
        if(i==m) minRight=nums2[j];
        else if(j==n) minRight=nums1[i];
        else minRight=getMin(nums1[i],nums2[j]);
        return ((double)(maxLeft+minRight))/2;
    }
    
    public int getMax(int a,int b){
        return a>b?a:b;
    }
    
    public int getMin(int a,int b){
        return a<b?a:b;
    }    
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值