码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 33. Search in Rotated Sorted Array

时间:2019-02-20 21:23:04      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:pre   指针   cat   end   sort   dex   tput   class   complex   

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.

Your algorithm‘s runtime complexity must be in the order of O(log n).

Example 1:

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

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

 

解法一:我的解法 指针移动查找 但是可能不符合O(logN)

class Solution {
    public int search(int[] nums, int target) {
        int i = 0;
        int l = nums.length;
        if(l == 0) return -1;
        if(l == 1 && target != nums[0]) return -1;
        if(target == nums[0]) return 0;
        else if(target > nums[0]) {
            i++;   
            while(i < l && nums[i-1] <= nums[i]){
                if(target == nums[i]) return i;
                i++;
            }
            if(i < l && target == nums[i]) return i;
        }else if(target < nums[0]) {
            i = l - 1;
            while(i > 0 && nums[i-1] <= nums[i]) {
                if(target == nums[i]) return i;
                i--;
            }
            if(i >= 0 && target == nums[i]) return i;
        }
        return -1;
    }
}

 

解法二:binary search

public int search(int[] A, int target) {
    int lo = 0;
    int hi = A.length - 1;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (A[mid] == target) return mid;
        
        if (A[lo] <= A[mid]) {
            if (target >= A[lo] && target < A[mid]) {
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        } else {
            if (target > A[mid] && target <= A[hi]) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
    }
    return A[lo] == target ? lo : -1;
}

 

leetcode 33. Search in Rotated Sorted Array

标签:pre   指针   cat   end   sort   dex   tput   class   complex   

原文地址:https://www.cnblogs.com/jamieliu/p/10409261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!