My C++ Binary Search Solution


  • 0
    M
    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            if(nums.size() == 0) return -1;
            int i = 0, j = int(nums.size()) - 1, mid = 0;
            while(i <= j) {
                mid = (i + j) / 2;
                if(nums[mid] == target) break;
                if(nums[i] <= nums[mid]) {
                    if (nums[i] <= target && target <= nums[mid]) j = mid - 1;
                    else i = mid + 1;
                }
                if(nums[mid] <= nums[j]) {
                    if(nums[mid] <= target && target <= nums[j])  i = mid + 1;
                    else j = mid - 1;
                }
            }
            return nums[mid] == target ? mid : -1;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.