704:二分查找
题目链接:https://leetcode.cn/problems/binary-search/
这个还是比较简单的
int search(vector
{
int low = 0;
int high = nums.size() - 1;
int mid = (low + high) / 2;
while(nums[mid] != target || low >= high)
{
if(nums[mid] < target)
{
low = mid + 1;
mid = (low + high) / 2;
}
else
{
high = mid - 1;
mid = (low + high) / 2;
}
}
return nums[mid]
}
27 移除元素
题目链接:https://leetcode.cn/problems/remove-element/
-
暴力解法
能自己写,但是有些细节还不太对,想了一下为什么需要i--,因为for循环里面操作执行完了之后,i++,但是数组又向前移了,所以需要i--
int removeElement(vector& 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];
}
size--;
i--;
}
}
return size;}
997 有序数组的平方
双指针法,看了讲解之后尝试自己写
nt i = 0;
int j = A.size() - 1;
vector
int k = result.size() - 1;
for(;i <= j;)
{
int left = A[i] * A[i];
int right = A[j] * A[j];
if(left < right)
{
result[k--] = right;
j--;
}
else
{
result[k--] = left;
i++;
}
}
return result;
- 双指针法
一开始尝试自己写,然后想法不对
int removeElement(vector& nums, int val)
{
int slow = 0;
int fast = 0;
for(; fast < nums.size(); fast++)
{
if(nums[fast] != val)
{
nums[slow++] = nums[fast];
}
}