1.二分查找类问题
704.二分查找
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;
}
};
2.原地修改类
27.移除元素
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if(nums.empty()) return 0;
int slow=0,fast=0;
while(fast<=nums.size()-1){
if(nums[fast]==val){
fast++;
}
else{
nums[slow++]=nums[fast++];
}
}
return slow;
}
};
977.有序数组的平方
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> result(nums.size());
int left=0,i=0,right=nums.size()-1;
while(left<=right){
if(abs(nums[left])>=abs(nums[right])){
result[i++]=nums[left]*nums[left];
left++;
}
else{
result[i++]=nums[right]*nums[right];
right--;
}
}
reverse(result.begin(),result.end());
return result;
}
};
3.滑动窗口类
209.长度最小的子数组
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int minLength=INT_MAX;
int slow=0,sum=0;
for(int fast=0;fast<nums.size();fast++){
sum+=nums[fast];
while(sum>=target){
minLength=min(minLength,fast-slow+1);
sum-=nums[slow++];
}
}
return minLength==INT_MAX? 0:minLength;
}
};
4.模拟类
59.螺旋矩阵II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n,vector<int>(n));
int num=1;
int up_bound=0,down_bound=n-1;
int left_bound=0,right_bound=n-1;
while(num<=n*n){
//上
if(up_bound<=down_bound){
for(int i=left_bound;i<=right_bound;i++){
result[up_bound][i]=num++;
}
up_bound++;//上边界下移
}
//右
if(left_bound<=right_bound){
for(int i=up_bound;i<=down_bound;i++){
result[i][right_bound]=num++;
}
right_bound--;//右边界左移
}
//下
if(up_bound<=down_bound){
for(int i=right_bound;i>=left_bound;i--){
result[down_bound][i]=num++;
}
down_bound--;//下边界上移
}
//左
if(left_bound<=right_bound){
for(int i=down_bound;i>=up_bound;i--){
result[i][left_bound]=num++;
}
left_bound++;//左边界右移
}
}
return result;
}
};