• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Search in Rotated Sorted Array

Suppose a sorted array 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,每次我们都可以切掉一半的数据,所以算法的时间复杂度是O(logn),空间复杂度是O(1)。

 

 1 class Solution {
 2     public int search(int[] nums, int target) {
 3         if (nums == null || nums.length == 0) return -1;
 4         int l = 0, r = nums.length - 1;
 5         while (l <= r) {
 6             int m = l + (r - l) / 2;
 7             if (nums[m] == target) return m;
 8             if (nums[m] >= nums[l]) {
 9                 // [l, m] is in order
10                 if (nums[l] <= target && target < nums[m]) {
11                     r = m - 1;
12                 }
13                 else l = m + 1;
14             }
15             else {
16                 // [m, r] is in order
17                 if (nums[m] < target && target <= nums[r]) {
18                     l = m + 1;
19                 }
20                 else r = m - 1;
21             }
22         }
23         return -1;
24     }
25 }

 

posted @ 2014-09-18 11:38  neverlandly  阅读(320)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3