Question about the Template II initial condition.

I find Template II a bit confusing about the initial condition right = nums.size(), can we change it to:

int binarySearch(vector& nums, int target){
if(nums.size() == 0)
return -1;

int left = 0, right = nums.size() - 1; // instead of nums.size()
while(left < right){
// Prevent (left + right) overflow
int mid = left + (right - left) / 2;
if(nums[mid] == target){ return mid; }
else if(nums[mid] < target) { left = mid + 1; }
else { right = mid; }
}

// Post-processing:
// End Condition: left == right
// Here no need to check out of boundary
if(nums[left] == target) return left;
return -1;
}

Comments (3)