zoukankan      html  css  js  c++  java
  • Leetcode 81. 搜索旋转排序数组 II

    题目链接

    https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/description/

    题目描述

    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

    ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。

    编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。

    示例 1:

    输入: nums = [2,5,6,0,0,1,2], target = 0
    输出: true
    
    

    示例 2:

    输入: nums = [2,5,6,0,0,1,2], target = 3
    输出: false
    

    题解

    和该系列题目的第一题一样,采用二分查找法,当最后跳出循环的时候,需要判断一下当前元素和target元素是否相等。

    代码

    class Solution {
        public boolean search(int[] a, int target) {
            if (a == null || a.length == 0) {
                return false;
            }
            int lo = 0, hi = a.length - 1;
            while (lo < hi) {
                int mid = (lo + hi) >> 1;
                if (a[mid] == target) { return true; }
                if (a[mid] > a[hi]) {
                    //考虑单调的一边
                    if (a[mid] > target && target >= a[lo]) { hi = mid; }
                    else lo = mid + 1;
                } else if (a[mid] < a[hi]) {
                    if (a[mid] < target && a[hi] >= target) {
                        lo = mid + 1;
                    } else {
                        hi = mid;
                    }
                } else {
                    hi--;
                }
            }
            return a[lo] == target ? true : false;
        }
    }
    
  • 相关阅读:
    UVA 10604 Chemical Reaction
    UVA 10635 Prince and Princess
    UVA 607 Scheduling Lectures
    Create Maximo Report
    安裝及配置Maximo Report步驟
    check blocking
    數據據類型縮寫
    .net
    poj3522
    poj1286
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9598613.html
Copyright © 2011-2022 走看看