Share my C++ solution,easy to understand


  • 0
    V

    https://leetcode.com/discuss/94195/share-my-c-solution-with-comment-easy-to-understand

    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            int n = nums.size();
            if (n == 0)
                return -1;
                
            int left = 0;
            int right = n - 1;
            int mid = 0;
            
            while (left <= right)
            {
                mid = left + (right-left) / 2;
                
                if (target == nums[mid])
                    return true;
                
                if (nums[left] < nums[mid])
                {
                    if (target >= nums[left] && target < nums[mid])
                        right = mid - 1;
                    else
                        left  = mid + 1;
                }
                else if (nums[left] > nums[mid])
                {
                    if (target > nums[mid] && target <= nums[right])
                        left = mid + 1;
                    else
                        right = mid - 1;
                }
                else
                    ++left;
            }
            
            return false;
        }
    };

Log in to reply
 

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