- 一个月通过练习掌握 算法入门知识
学习内容:
- 数据结构与算法
学习时间:
- 周一至周五晚上 7 点—晚上9点
- 周六上午 9 点-上午 11 点
- 周日下午 3 点-下午 6 点
学习产出: 第1天数组 2022.06.01
1588. 所有奇数长度子数组的和
int sumOddLengthSubarrays(int* arr, int arrSize){
int res = 0;
int size = 1;
if(size <= arrSize)
{
while(size <= arrSize)
{
for(int i = 0; size + i -1 < arrSize; i++)
{
for(int j = 0; j < size; j++)
{
res += arr[i+j];
}
}
size += 2;
}
}
return res;
}
1848. 到目标元素的最小距离
class Solution {
public:
int getMinDistance(vector& nums, int target, int start) {
vector targets;
for(int i = 0; i< nums.size(); i++)
{
if(nums[i] == target)
targets.push_back(i);
}
sort(targets.begin(),targets.end(),[&start](int a, int b){return abs(a - start) < abs(b - start);});
return abs(targets[0] - start);
}
};
1652. 拆炸弹
class Solution {
public:
vector decrypt(vector& code, int k) {
int codeSize= code.size(); // 防止被修改影响循环数组
vector reses(codeSize);
for(int i = 0; i< codeSize; i++)
{
if(k > 0)
{
int idx = 0;
int res = 0;
for(int j = 1; j<= k; j++)
{
if(i + j < codeSize)
{
idx = i + j;
}
else
{
idx = (i + j)% codeSize; //%
}
res += code[idx];
}
reses[i] = res;
}
else if(k < 0)
{
int idx = 0;
int res = 0;
for(int j = 1; j<= abs(k); j++)
{
if(i - j >= 0)
{
idx = i - j;
}
else
{
idx = codeSize - (j -i);
}
res += code[idx];
}
reses[i] = res;
}
else
{
code[i] = 0;
}
}
return reses;
}
};
1640. 能否连接形成数组
class Solution {
public:
bool canFormArray(vector& arr, vector>& pieces) {
bool result = true;
bool res = false;
int size = 0;
for(int i = 0; i< pieces.size(); i++)
{
for(int n = 0; n< arr.size(); n++)
{
if(pieces[i][0] == arr[n])
{
size++;
res = true;
for(int j = 1; j< pieces[i].size(); j++)
{
//不允许 对每个数组 pieces[i] 中的整数重新排序
if(pieces[i][j] == arr[n+j])
{
size++;
}
else
{
return false;
}
}
}
}
}
if(size != arr.size())
{
return false;
}
return result&res;
}
};



