zoukankan      html  css  js  c++  java
  • LeetCode:(Array-33)Search in Rotated Sorted Array

    去哪网面试题:二分查找的变形题目

      目的是为了在O(logn)的时间复杂度下解决此问题,所以用二分查找。

     1 package com.hb.leetcode;
     2 
     3 
     4 /*
     5  * Search in Rotated Sorted  Array
     6  * 
     7  * Suppose a sorted array is rotated at some pivot unknown to you beforehand.
     8  * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
     9  * You are given a target value to search. 
    10  * If found in the array return its index, otherwise return -1.
    11  * You may assume no duplicate exists in the array.
    12  * 
    13  */
    14 
    15 public class SearchInRotated {
    16     
    17     public  static int search(int[] A , int  target){
    18         return rec( A , target , 0 , A.length -1 );
    19     }
    20      
    21     public  static int rec(int[]  A , int target , int  low , int  high){
    22         if(low > high){  //没找到的情况
    23             return -1 ;  
    24         } 
    25         
    26         int  mid = low + (high - low) / 2 ;
    27         
    28         if(A[mid] == target){  //找到了
    29             return mid;
    30         }
    31         
    32         int res = rec(A , target , low , mid -1 );  //在左侧查找 
    33         
    34         if(res == -1 ){  //如果左侧没有找到,继续在右侧查找
    35             res = rec(A , target , mid + 1 , high ); 
    36         }
    37         
    38         
    39         return res;
    40     }
    41     
    42     public static void main(String[] args) {
    43         int[]  A = { 2, 3, 4, 5, 6, 0 ,1};
    44         System.out.println(search(A, 0));
    45     }
    46     
    47     
    48 
    49 }
  • 相关阅读:
    Window服务的创建与删除
    remoting 中事件找不到订阅者时引发异常的解决办法
    TCP/IP 的一些常识
    JDK ByteBuffer & MINA IoBuffer 总结
    web协议总结
    NIO VS IO
    MINA TCP 粘包 少包最终解决方案
    NIO 之 通道
    流式套接字(TCP)和 数据报套接字(UDP)的区别
    MINA 异步 读写总结
  • 原文地址:https://www.cnblogs.com/Mokaffe/p/4360805.html
Copyright © 2011-2022 走看看