Home Leetcode 0033 Search in Rotated Sorted Array
Post
Cancel

Leetcode 0033 Search in Rotated Sorted Array

Search in Rotated Sorted Array problem results

Search in Rotated Sorted Array

Result

First Blood

I got a wrong answer because I forget to check if the pivot number is equal to the target.

Double Kill

First, find the pivot index, if no pivot index was found, the array is not rotated, do a binary search on the whole array. Then check the target with the pivot number, to decide to do a binary search on which part of the array.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
{
    class Solution {
public:
    int search(vector<int>& nums, int target) {
              int pivot = nums[0];
        int size = nums.size();
        if(size == 1)
        {
            return target == pivot ? 0 : -1;
        }

        int i = 0;
        //find pivot index
        for(i = 0; i < size; i++)
        {
            if(nums[i] < pivot)
            {
                break;
            }
        }
        int low = 0;
        int high = 0;
        //the array is not rotated
        if(i == size)
        {
            //Do binary search on whole array
            low = 0;
            high = size -1;
            
        }
        else
        {
            //pivot index is i-1;
            //check target on which side of pivot index
            if(target >= pivot)
            {
                low = 0;
                high = i-1;
            }
            else
            {
                low = i;
                high = size-1;
            }
        }

        int j = 0;
        while(low<=high)
        {
            j = (low + high)/2;

            if(nums[j] == target)
            {
                return j;
            }
            else if(nums[j] < target)
            {
                low = j + 1;
            }
            else
            {
                high = j - 1;
            }
        }

        return -1;  
    }
};
}
This post is licensed under CC BY 4.0 by the author.
Trending Tags