博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Search in Rotated Sorted Array
阅读量:7219 次
发布时间:2019-06-29

本文共 1542 字,大约阅读时间需要 5 分钟。

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.

Binary Search

Time Complexity

O(logn)
Space Complexity
O(1)

思路

If target == nums[mid]; return mid;

If target nums[mid] < nums[right], mid to right is sorted, so we just need to know if target is between mid to right.
If target nums[mid] > nums[right], left to mid is sorted, so we just need to know if target is between left to mid.

代码

public int search(int[] nums, int target) {    if(nums == null || nums.length == 0){        return -1;    }    int start = 0, end = nums.length - 1;    while(start + 1 < end){        int mid = start + (end - start)/2;        if(nums[mid] == target){            return mid;        }        if(nums[mid] < nums[end]){    //right part is sorted            if(nums[mid] < target && target <= nums[end]){                start = mid + 1;            }else{                end = mid - 1;            }        }else if(nums[mid] > nums[end]){   //left part is sorted            if(nums[start] <= target && target < nums[mid]){                end = mid - 1;            }else{                start = mid + 1;            }        }else{            start++;        }    }    if(nums[start] == target){        return start;    }    if(nums[end] == target){        return end;    }    return -1;}

转载地址:http://xoxym.baihongyu.com/

你可能感兴趣的文章
速成CAD版本转换的教程
查看>>
CAD文件图纸过大,该怎么解决?
查看>>
Spring aop 切不进去原因。。
查看>>
PHP获取客户端IP
查看>>
php开发APP接口-封装通信接口改进版
查看>>
Android系统性能演变历程
查看>>
OSChina 周三乱弹 —— 打醒精神去瞌睡
查看>>
SSH 密钥登录linux
查看>>
你必须掌握的 21 个 Java 核心技术!
查看>>
告诉你WHT中文站是什么?
查看>>
4、Juniper SSG520 PPTP映射到ROS后MAC无法连接解决方法
查看>>
利用批处理文件来建立一个记录3389登陆者信息
查看>>
Linux 系统下双机HA的实现
查看>>
02_swarm mode key concepts
查看>>
Eclipse打包插件Fat Jar 解压打包
查看>>
Apache Shiro 使用手册
查看>>
CentOS mini 6.5 安装DB2 Express-C 问题处理记录
查看>>
DirectByteBuffer
查看>>
Docker Compose文件详解 V2
查看>>
Memcached的原理与应用(未完)
查看>>