原力扣704题目链接
力扣704 二分查找
笔者第一次的暴力写法
class Solution {
public:
int search(vector<int>& nums, int target) {
int size = nums.size();
int mid = size /2;
int index = -1;
if(target > nums[mid])
{
for(int i =mid;i<size;i++)
{
if(target == nums[i])
{
index = i;
break;
}
}
}
else
{
for(int i =mid;i >=0;i--)
{
if(target == nums[i])
{
index = i;
break;
}
}
}
return index;
}
};
查看解析后
左闭右闭
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)/2;
if(nums[mid] > target)
{
right = mid-1;
}else if(nums[mid] < target)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
};
左闭右开
class Solution {
public:
int search(vector<int>& nums, int target) {
int left =0;
int right = nums.size();
while(left < right)
{
int mid = (left + right)/2;
if(nums[mid] > target)
{
right = mid;
}
else if(nums[mid] < target)
{
left = mid +1;
}
else
{
return mid;
}
}
return -1;
}
};
- 移除元素
移除元素
暴力写法
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
std::sort(nums.begin(),nums.end());
for(std::vector<int>::iterator it = nums.begin();it!=nums.end();)
{
if(*it == val)
{
it = nums.erase(it);
}
else
{
it++;
}
}
int length = nums.size();
return length;
}
};
修改后:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow =0;
for(int fast =0;fast<nums.size();fast++)
{
if(nums[fast]!=val)
{
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
};