701.二分查找
题目链接:https://leetcode.cn/problems/binary-search/description/
暂时没有深入研究边界条件(明天补),对于折半查找的代码,考研时复习过,上手写才发现掌握还是不牢靠。
class Solution {
public:
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){
high = mid - 1;
}else if(nums[mid] < target){
low = mid + 1;
}else{
return mid;
}
}
return -1;
}
};
视频链接:https://www.bilibili.com/video/BV1fA4y1o715/
文章讲解:https://programmercarl.com/%E6%95%B0%E7%BB%84%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html
27. 移除元素
题目链接:https://leetcode.cn/problems/remove-element/description/
这道题我最开始外层用的while循环,与for循环相比,while还是更适合于链表,最致命的错误是在覆盖当前元素后,没有将i返回到当前元素前一个位置,若相连两个元素等于val,此时后一个覆盖前一个后,i++继续往后执行,就会将原来漏删val元素 。
暴力解:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0;
int n = nums.size();
for(i; i < n; i++){
if(nums[i] == val){
for(int j = i; j < n - 1; j++){
nums[j] = nums[j+1];//
}
n--;
i--;
}
}
return n;
}
};
双指针解:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
//快慢指针解法
int fast,last = 0;
for(fast = 0; fast < nums.size(); fast++){
if(nums[fast] != val){
nums[last] = nums[fast];
last++;
}
}
return last;
}
};
这种解法真的很实用,核心就是越过要删去的元素,将原来数组中非val值元素插入到“新数组中”。