算法训练营打卡day1
704.二分查找 https://leetcode.cn/problems/remove-element/
法一:区间左闭右闭[left,right]
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while(left <= right)
{
int mid = left + (right - left)/2;
if(nums[mid] < target)
{
left = mid + 1;
}
else if(nums[mid] > target)
{
right = mid - 1;
}
else{
return mid;
}
}
return -1;
}
};
法二:左闭右开[left,right)
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size();
while(left < right) //作闭又开区间,相等无效啊啊啊,因为不可能取到右边啊!!
{
int mid = left + (right - left)/2;
if(nums[mid] < target)
{
left = mid + 1;
}
else if(nums[mid] > target)
{
right = mid; //这里是左闭又开区间了,所以反正不会等于right,别再减1了
}
else{
return mid;
}
}
return -1;
}
};
27. 移除元素https://leetcode.cn/problems/remove-element/submissions/
暴力法:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for(int i = 0;i < size;i++)
{
if(nums[i] == val)
{
for(int j = i + 1;j < size;j++) #一个一个往前移
{
nums[j - 1] = nums[j];
}
i--;
size--;
}
}
return size;
}
};
快慢指针:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int k = 0;
for(int i = 0;i < nums.size();i++)
{
if(nums[i] != val)
{
nums[k++] = nums[i];
}
}
return k;
}
};