contains category wise problems(data structures, competitive) of popular platforms.
View the Project on GitHub mayankdutta/category-wise-problems
array
, so it’s better to start from outside of the ranges.-1
and high from nums.size()
.boundary cases
.mid
.TLEs
due to strange jumps, we have condition low + 1 < high
int search(vector<int>& nums, int target) {
int low = -1;
int high = nums.size();
while (low + 1 < high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
}
else if (target < nums[mid]) {
high = mid;
}
else {
low = mid;
}
}
return -1;
}
int search(vector<int>& nums, int target) {
int low = 0;
int high = nums.size() - 1;
for (int t = 0; t < 50; t++) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
}
else if (target < nums[mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}
low
, high
.mid - 1
, or mid + 1
.low + 1 < high
int search(vector<int>& nums, int target) {
int low = 0;
int high = nums.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
}
else if (target < nums[mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}