zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array

    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).

    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.

     1 public class Solution {
     2     public int search(int[] nums, int target) {
     3         int low = 0, high = nums.length - 1;
     4         while (low <= high) {
     5             int mid = low + (high - low) / 2;
     6             if (nums[mid] == target) return mid;
     7             
     8             if (nums[mid] > target) {
     9                 if (nums[mid] > nums[high] && nums[high] >= target)
    10                     low = mid + 1;
    11                 else
    12                     high = mid - 1;
    13             } else {
    14                 if (nums[mid] < nums[high] && nums[high] < target)
    15                     high = mid - 1;
    16                 else
    17                     low = mid + 1;
    18             }
    19         }
    20         
    21         return -1;
    22     }
    23 }
  • 相关阅读:
    __del__ 析构方法 __init__ 构造方法
    单态模式
    面向对象小练习2
    __new__ '''魔术方法
    菱形继承
    继承:多继承
    继承: .单继承
    面向对象小练习
    __init__ 魔术方法
    如何访问私有成员
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6660631.html
Copyright © 2011-2022 走看看