题目 | 链接 | 难度 |
---|---|---|
704. 二分查找 | https://leetcode-cn.com/problems/binary-search/ | 简单 |
35. 搜索插入位置 | https://leetcode-cn.com/problems/search-insert-position/ | 简单 |
278. 第一个错误的版本 | https://leetcode-cn.com/problems/first-bad-version/ | 简单 |
704. 二分查找
我的AC代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
int start_idx = 0, end_idx = nums.size() - 1, mid_idx;
int mid_num;
while (start_idx <= end_idx) {
mid_idx = (start_idx + end_idx) / 2;
mid_num = nums[mid_idx];
if (mid_num == target)
return mid_idx;
else if (mid_num < target)
start_idx = mid_idx + 1;
else
end_idx = mid_idx - 1;
}
return -1;
}
};
我的另一个AC代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
int start_idx = 0, end_idx = nums.size() - 1, mid_idx;
int start_num, end_num, mid_num;
while (start_idx <= end_idx) {
start_num = nums[start_idx];
end_num = nums[end_idx];
if (start_num == target)
return start_idx;
else if (end_num == target)
return end_idx;
else {
mid_idx = (start_idx + end_idx) / 2;
mid_num = nums[mid_idx];
if (mid_num == target)
return mid_idx;
else if (mid_num < target) {
start_idx = mid_idx + 1;
end_idx = end_idx - 1;
}
else {
start_idx = start_idx + 1;
end_idx = mid_idx - 1;
}
}
}
return -1;
}
};
35. 搜索插入位置
我的AC代码:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int start_idx = 0, end_idx = nums.size() - 1, mid_idx;
int start_num = nums[start_idx], end_num = nums[end_idx], mid_num;
if (target > end_num)
return end_idx + 1;
else if (target < start_num)
return 0;
while (start_idx <= end_idx) {
mid_idx = (start_idx + end_idx) / 2;
mid_num = nums[mid_idx];
if (mid_num == target)
return mid_idx;
else if (mid_num < target)
start_idx = mid_idx + 1;
else
end_idx = mid_idx - 1;
}
if(nums[mid_idx] < target)
return mid_idx + 1;
else
return mid_idx;
}
};
278. 第一个错误的版本
注意数值范围,故用unsigned int。
我的AC代码:
class Solution {
public:
int firstBadVersion(unsigned int n) {
unsigned int start_idx = 1, end_idx = n, mid_idx;
bool start_stat = isBadVersion(start_idx), end_stat = isBadVersion(end_idx), mid_stat;
while (end_idx - start_idx > 1) {
mid_idx = (start_idx + end_idx) / 2;
mid_stat = isBadVersion(mid_idx);
if (!mid_stat)
start_idx = mid_idx;
else
end_idx = mid_idx;
}
if (start_stat)
return start_idx;
else
return end_idx;
}
};