//704.二分查找
class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0;
int right=nums.size()-1;
while(left<=right){
int mediu=left+(right-left)/2;
if(nums[mediu]==target){
return mediu;
}
if(nums[mediu]<target){
left=mediu+1;
}
else if(nums[mediu]>target){
right=mediu-1;
}
}
return -1;
}
};
//27.移除元素
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
//双指针法
int slowidx=0;
for(int fastidx=0;fastidx<nums.size();fastidx++){
if(nums[fastidx]!=val){
nums[slowidx++]=nums[fastidx];
}
}
return slowidx;
}
};
//209长度最小的子数组
class Solution {//暴力解法
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result=INT_MAX;
int length;
for(int i=0;i<nums.size();i++){
int sum=0;
for(int j=i;j<nums.size();j++){
sum+=nums[j];
if(sum>=target){
length=j-i+1;
result=(result>length)?length:result;
break;
}
}
}
return result==INT_MAX?0:result;
}
};
//滑动窗口
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result=INT_MAX;
int length;
int i=0;//起始位置
int sum=0;
for(int j=0;j<nums.size();j++){
sum+=nums[j];
while(sum>=target){
length=j-i+1;
result=(result>length)?length:result;
sum-=nums[i++];
}
}
return result==INT_MAX?0:result;
}
};
|