LeetCode 704
思路:
1.在左闭右闭区间[left,right]上做二分查找,故循环条件为(left<=right)。
2.mid值用(left+right)/2取得
class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0,right=nums.size()-1;
while(left<=right){
int mid=(left+right)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]<target){
left=mid+1;
}
else right=mid-1;
}
return -1;
}
};
3.在左闭右开区间[left,right)上做二分查找,故循环条件为(left<right)
4.if (nums[middle] > target) right 更新为 middle
class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0,right=nums.size();
while(left<right){
int mid=(left+right)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]<target){
left=mid+1;
}
else right=mid;
}
return -1;
}
};
LeetCode 35
题目链接:35. 搜索插入位置 - 力扣(LeetCode)
思路:在二分查找的基础上多加一个判断插入位置的逻辑
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i=0,j=nums.size()-1;
while(i<=j){
int mid=(i+j)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]<target){
i=mid+1;
}
else j=mid-1;
}
return j+1;
}
};
LeetCode 27
思路:
暴力解法,用两个for循环求解
时间复杂度:O(n^2)
空间复杂度:O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int count=nums.size();
for(int i=0;i<count;i++){
if(nums[i]==val){
for(int j=i+1;j<count;j++){
nums[j-1]=nums[j];
}
i--;
count--;
}
}
return count;
}
};
2.双指针法,设置快慢指针,当快指针所指向的元素不等于题目所给val值,将快指针处元素赋予慢指针处,并将慢指针往后移一位
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i=0,j=0;
int size=nums.size();
while(j<size){
if(nums[j]!=val){
nums[i++]=nums[j];
}
j++;
}
return i;
}
};