Simple solution using binary search in 5 lines


  • 1
    R

    Using the ternary operator, I check for the index using standard binary search.

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

Log in to reply
 

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