https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html
二分查找
状态:使用暴力法
思路:使用for循环遍历数组中每个元素,找到值
进阶解法:先判断中间值是否大于target,如果大于则在前半部分再使用二分法查找,以此类推,这样可以减少时间复杂度
看了题解后:对二分法知识基本不会,看了后才了解
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
while (left <= right) {
int middle = (left + right)/2;
if (nums[middle] < target){
left = middle + 1;
}
else if (nums[middle] > target) {
right = middle - 1;
}
else {
return middle;
}
}
return -1;
}
};
打代码要注意{},养成好习惯
//解法二,左闭右开
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size();
while (left < right) {
int middle = (left + right)/2;
if (nums[middle] < target){
left = middle + 1;
}
else if (nums[middle] > target) {
right = middle;
}
else {
return middle;
}
}
return -1;
}
};
移除元素
思路是暴力解法,但是不会删除数组中的元素,后来知道是将后面的全往前移一位
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len = nums.size();
for (int i = 0; i < len; i++) {
if (nums[i] == val) {
for (int j = i + 1; j < len; j++) {
nums[j-1] = nums[j];
}
i--;
len--;
}
}
return len;
}
};
双指针法,看一遍视频讲解理解
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++){
if (val != nums[fastIndex]){
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};