LeetCode 33 Search in Rotated Sorted Array (C++, Python)

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.

Solution C++


 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
class Solution {
public:
    int search(int A[], int n, int target) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (A[mid] == target) return mid;
            bool searchLeft = false;
            if (A[mid] > A[high]) {
                if ((A[mid] > target) && (target >= A[low])) {
                    searchLeft = true;
                }
            } else if (A[mid] < A[low]) {
                if ((A[mid] > target) ||((A[mid] < target) && target > A[high])) {
                    searchLeft = true;
                }
            } else {
                if (A[mid] > target) searchLeft = true;
            }
            if (searchLeft) high = mid - 1;
            else low = mid + 1;
        }
        return -1;
    }
};

Solution Python


 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
class Solution:
    def intSearch(self, A, target, low, high):
        if low > high: return -1
        mid = (low + high) / 2
        if A[mid] == target: return mid
        leftPart = False
        rightPart = False
        if A[mid] > A[high]: leftPart = True
        if A[mid] < A[low]: rightPart = True
        searchLeft = False
        if not leftPart and not rightPart:
            if A[mid] > target:
                searchLeft = True
        elif leftPart:
            if target == A[low]: return low
            if A[mid] > target > A[low]:
                searchLeft = True
        elif rightPart:
            if target == A[high]: return high
            if A[mid] > target or A[mid] < target > A[high]:
                searchLeft = True
        if searchLeft:
            return self.intSearch(A, target, low, mid - 1)
        else:
            return self.intSearch(A, target, mid + 1, high)
        
    # @param A, a list of integers
    # @param target, an integer to be searched
    # @return an integer
    def search(self, A, target):
        return self.intSearch(A, target, 0, len(A) - 1)

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving