clueless coding // TODO: be smarter

LeetCode Search in Rotated Sorted Array: CPP Solution



TL;DR Code Solution


int search(vector<int>& nums, int target) {

    int left = 0;
    int right = (int)nums.size() - 1;

    while (left <= right) {

        int middle = (left + right) / 2;
        if (nums[middle] == target) {
            return middle;
        }

        if (nums[left] <= nums[middle]) {
            if (target < nums[middle] && target >= nums[left])
                right = middle - 1;
            else 
                left = middle + 1;
        }

        if (nums[middle] <= nums[right]) {
            if (target > nums[middle] && target <= nums[right])
                left = middle + 1;
            else 
                right = middle - 1;

        }

    }
    return -1;
}