一、Leetcode 二分查找
做题思路:
- 应用二分法的条件是:数组为有序数组且数组中无重复的元素。
- 区别使用:while(Left <= Right),while(Left < Rifht),while(Left == Right);Middle = Right - 1,Middle = Right;
- 二分法区分定义:左闭右闭[Left,Right],左闭右开[Left,Right);
第一眼看题目的想法:
因为数据与结构算法学的不好,第一眼看的毫无思路,希望后续逐渐的刷题中能够提高自己的水平。
看完代码随想录的想法&做题中遇到的难点:
- 理解nums.size() - 1中为什么要减1。
- 理解right = middlle - 1;left = middle + 1。
- 理解Middle在while(Left <= Right) 中重置。
代码如下(左闭右闭):
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 - Left)/2);
if(nums[Middle] > target)
{
Right = Middle - 1;
}
else if(nums[Middle] < target)
{
Left = 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 - Left) >> 1);
if(nums[Middle] > target)
{
Right = Middle;
}
else if(nums[Middle] < target)
{
Left = Middle + 1;
}
else
{
return Middle;
}
}
return -1;
}
};
二、LeetCode27 移除元素
做题思路:
- 首先要知道数组在内存中的地址是连续的,不能单独删除某个元素。
- 暴力解法
- 双指针法
- 相向双指针法
- 注:由于时间有限仅仅学习尝试了数组和链表更为普遍的双指针法
第一眼看题目的想法:
因为数据与结构算法学的不好,第一眼看的毫无思路,希望后续逐渐的刷题中能够提高自己的水平。
看完代码随想录的想法&做题中遇到的难点:
- 快慢指针各自的含义以及作用。
- 如何实现原地删除以及返回新数组的长度。
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;
}
};