Post

33 Search In Rotated Sorted Array

33 Search In Rotated Sorted Array

Search in Rotated Sorted Array image

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left rotated by 3 indices and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of *target if it is in nums, or -1 if it is not in *nums.

You must write an algorithm with O(log n) runtime complexity.

 

Example 1:

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

Example 2:

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

Example 3:

1
2
3
**Input:** nums = [1], target = 0
**Output:** -1

 

Constraints:

1
2
3
4
5
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
All values of nums are **unique**.
nums is an ascending array that is possibly rotated.
-104 <= target <= 104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

impl Solution {
    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        
        let mut rotate = 0;
        for i in 0..nums.len()-1 {
            if nums[i] > nums[i + 1] {
                rotate = i + 1;
                break;
            }
        }
        print!("{}", rotate);
        let mut left = 0;
        let mut right = nums.len() - 1;

        if target >= nums[0] && rotate != 0 {
            // item lies before rotate
            right = rotate - 1;
            while left < right {
                let mid = left + (right - left) / 2;
                if nums[mid] < target {
                    left = mid + 1;
                } else {
                    if mid == 0 { break; }
                    right = mid;
                }
            }

        } else {
            //item lies after rotate
            left = rotate;
            while left < right {
                let mid = left + (right - left) / 2;
                if nums[mid] == target {
                    left = mid;
                    break;
                }
                if nums[mid] < target {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
        }
        print!("{} {}", left, right);
        if nums[left] != target {
            return -1;
        }

        return left as i32;
    }
}



This post is licensed under CC BY 4.0 by the author.