zoukankan      html  css  js  c++  java
  • 81. Search in Rotated Sorted Array II (中等)

    Suppose an array sorted in ascending order 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).

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

    The array may contain duplicates.

    这种题自我感觉比较难.仍遵循二分查找的整体框架:

    以 [4 5 6 7 0 1 2] 为例
    
    while(lo < hi){
        case1: A[mid] > A[hi] 这时,看看 ta 在 4...mid 之间吗?
        case2: A[mid] < A[hi] 这时,看看 ta 在 mid...2 之间吗?
        case3: A[mid] == A[hi] 这时, hi--;
    }
    

    人家思想,自个代码:
    (O(logn)) time, (O(1)) extra space.

    bool search(vector<int>& A, int ta) {
    	const int n = A.size();
    	if (n == 0) return false; // special case
    	int lo = 0, hi = n - 1;
    
    	while (lo < hi) {
    		int mid = lo + ((hi - lo) >> 1);
    		if (A[mid] == ta) return true;
    		if (A[mid] > A[hi]) {
    			if (ta < A[mid] && ta >= A[lo]) hi = mid;
    			else lo = mid + 1;
    		} else if (A[mid] < A[hi]) {
    			if (ta > A[mid] && ta <= A[hi]) lo = mid + 1;
    			else hi = mid;
    		} else hi--;
    	}
    	return ta == A[lo] ? true : false;
    }
    
  • 相关阅读:
    memcached使用入门
    winform代码生成器(三)
    Spark + sbt + IDEA + HelloWorld + MacOS
    CentOS下Hive搭建
    36. 有效的数独
    HADOOP依赖
    判别数字图片能否「一笔完成」
    【网易微专业】图表绘制工具Matplotlib
    【18.065】Lecture2
    【18.065】Lecture1
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7444577.html
Copyright © 2011-2022 走看看