01二分查找
#include <iostream>
#include <vector>
using namespace std;
int search_arr(vector<int>& arr, int target, int low, int high){
int flag = (low + high) / 2;
if(low < high){
if(target == arr[flag])
return flag;
if(target < arr[flag])
return search_arr(arr, target, low, flag - 1);
if(target > arr[flag])
return search_arr(arr, target, flag + 1, high);
}
return -1;
}
int main(){
vector<int> arr = {0,1,2,3,4,5,6,7,13,16};
cout << search_arr(arr, 13, 0, arr.size());
}
02移除元素
#include <iostream>
#include <vector>
using namespace std;
//暴力搜索
void remove_nums1(vector<int>& arr, int target){
int size = arr.size();
for (size_t i = 0; i < arr.size(); i++){
if(arr[i] == target){
for (size_t j = i; j < arr.size() - 1; j++){
arr[j] = arr[j + 1];
}
size--;
i--;
}
}
arr.resize(size);
}
//双指针法
void remove_nums2(vector<int>& arr, int target){
int slow = 0;
for (int fast = 0; fast < arr.size(); fast++){
if(target != arr[fast]){
arr[slow++] = arr[fast];
}
}
arr.resize(slow);
}
int main(){
vector<int> arr = {1,3,1,1,1,1,1,1,2,3,5,6,7,8};
remove_nums1(arr, 1);
for (size_t i = 0; i < arr.size(); i++)
{
cout << arr[i] << " ";
}
}
03长度最小子数组
//2024.1.16
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
//暴力解法
int a(vector<int>& arr, int s){
int min = arr.size() + 1;
int sum = 0;
int len = 0;
for (size_t i = 0; i < arr.size(); i++)
{
sum = 0;
for (size_t j = i; j < arr.size(); j++)
{
sum += arr[j];
if(sum >= s){
len = j - i + 1;
min = min > len ? len : min;
break;
}
}
}
return min == (arr.size() + 1) ? 0 : min;
}
//滑动窗口
int b(vector<int>& arr, int s){
int min = arr.size() + 1;
int sum = 0;
int len = 0;
int i = 0;
for (size_t j = 0; j < arr.size(); j++)
{
sum += arr[j];
while(sum >= s){
len = j - i + 1;
min = min < len ? min : len;
sum -= arr[i++];
}
}
return min == (arr.size() + 1) ? 0 : min;
}
int main(){
vector<int> arr = {1,3,5,7,9,12};
cout << b(arr, 28) << endl;
}
04螺旋矩阵
//2024.1.25,
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> a(int n){
vector<vector<int>> res(n, vector<int>(n, 0));
int startx = 0, starty = 0;
int loop = n / 2;
int mid = n / 2;
int count = 1;
int offset = 1;
int i, j;
while(loop--){
i = startx;
j = starty;
for (j = starty; j < startx + n - offset; j++)
{
res[startx][j] = count++;
}
for (i = startx; i < startx + n - offset; i++)
{
res[i][j] = count++;
}
for (; j > starty; j--)
{
res[i][j] = count++;
}
for (; i > startx; i--)
{
res[i][j] = count++;
}
startx++;
starty++;
offset += 2;
}
if(n % 2){
res[mid][mid] = count;
}
return res;
}
int main(){
vector<vector<int>> arr = a(20);
for(auto i = arr.begin(); i != arr.end(); i++){
for (auto j = (*i).begin(); j != (*i).end(); j++)
{
cout << *j << " ";
}
cout << endl;
}
}