数组理论
数组是存放在连续内存空间上的相同类型数据的集合
数组的下标是从0开始的
数组内存空间的地址是连续的
数组的元素是不能删除的,只能覆盖
Leetcode704 二分查找 Binary Search
左闭右闭 [left,right]
while(left <= right)
if (nums[middle] > target) right要赋值为middle - 1. 因为nums[middle] 一定不是target所以查找的就是middle - 1
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right){
int middle = left + ((right - left) >> 1);
if (nums[middle] > target){
right = middle - 1;
} else if (nums[middle] < target){
left = middle + 1;
} else if (nums[middle] == target){
return middle;
}
}
return -1;
}
};
左闭右开[left,right)
while(left < right)
if (nums[middle] > target) right要赋值为middle. 因为寻找左闭右开区间, 所以right是middle
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size();
while (left < right){
int middle = left + ((right - left) >> 1);
if (nums[middle] > target){
right = middle;
} else if (nums[middle] < target){
left = middle + 1;
} else if (nums[middle] == target){
return middle;
}
}
return -1;
}
};
Leetcode27 移除元素 Remove Element
暴力解法
(目前Leetcode显示Time Limit Exceeded)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for (int i = 0; i < nums.size(); i++){
if (nums[i] == val){
for (int j = i + 1; j < size ; j++){
nums[j - 1] = nums[j];
}
i--;
size--;
}
}
return size;
}
};
双指针法
因为可以改变数组顺序,只要慢指针找到了val的值我们就可以把快指针的数值赋值到慢指针上,并且快指针-1. 最后输出快指针就可以.
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int left = 0, right = nums.size();
while (right > left){
if (nums[left] == val){
nums[left] = nums[right - 1];
right--;
} else {
left++;
}
}
return right;
}
};