704. 二分查找

Ctrl + 鼠标左键单击题目文本就能跳转到leetcode对应的题目,因此不在这里附上原题文本.

题解:

https://leetcode.cn/problems/binary-search/solutions/2770440/704-er-fen-cha-zhao-by-joker-ek4-84yy

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 (target < nums[middle])
right = middle - 1;
else if (target > nums[middle])
left = middle + 1;
else
return middle;
}
return -1;
}
};

相关题目推荐

27. 移除元素

题解:

参考自己的这篇博客

https://leetcode.cn/problems/remove-element/solutions/2769826/27-yi-chu-yuan-su-by-joker-ek4-1wx5

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 双指针,快慢指针。
/*
犯下的低级错误,在main函数里面调用了两次removeElement(nums, 2)
导致第一次j是6第二次j变成9了
*/
class Solution {
public:
int removeElement(vector<int> &nums, int val)
{
int j = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] != val)
{
nums[j] = nums[i];
j++;
}
}
return j;
}
};

相关题目推荐