zoukankan      html  css  js  c++  java
  • [LC] 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,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

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

    Example 1:

    Input: nums = [2,5,6,0,0,1,2], target = 0
    Output: true
    

    Example 2:

    Input: nums = [2,5,6,0,0,1,2], target = 3
    Output: false

    class Solution {
        public boolean search(int[] nums, int target) {
            if (nums == null || nums.length == 0) {
                return false;
            }
            int start = 0, end = nums.length - 1;
            while (start + 1 < end) {
                int mid = start + (end - start) / 2;
                // move the left if equal with mid value
                while (start < mid && nums[start] == nums[mid]) {
                    start += 1;
                }
                if (nums[start] <= nums[mid]) {
                    if (nums[start] <= target && target <= nums[mid]) {
                        end = mid;
                    } else {
                        start = mid;
                    }
                } else {
                    if (nums[mid] <= target && target <= nums[end]) {
                        start = mid;
                    } else {
                        end = mid;
                    }
                }
            }
            if (nums[start] == target) {
                return true;
            }
            if (nums[end] == target) {
                return true;
            }
            return false;
        }
    }
  • 相关阅读:
    p1706 全排列
    2089烤鸡(类似于选数问题)
    1036选数
    bfs
    A-E
    A-3
    百题A-2
    百题A-1
    二级概念题
    随记
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12020965.html
Copyright © 2011-2022 走看看