【每日刷题】Day32
🥕个人主页:开敲🍉
🔥所属专栏:每日刷题🍍
🌼文章目录🌼
1. 1652. 拆炸弹 - 力扣(LeetCode)
2. 2058. 找出临界点之间的最小和最大距离 - 力扣(LeetCode)
3. 2181. 合并零之间的节点 - 力扣(LeetCode)
1. 1652. 拆炸弹 - 力扣(LeetCode)
//0ms 100%思路:分类讨论,暴力遍历。创建新数组存储替换后的数字,因为是循环数组,因此需要往复遍历数组。
int* decrypt(int* code, int codeSize, int k, int* returnSize)
{
int* arr = (int*)malloc(sizeof(int)*101);
memset(arr,0,sizeof(int)*101);
if(k>0)//k>0,将后k个数字相加作为当前位置数字
{
for(int i = 0;i<codeSize;i++)
{
int sum = 0;
int j = i+1;
int tmp = k;
while(tmp)
{
if(j==codeSize)//如果遇到数组尾,重置为0
{
j = 0;
}
sum+=code[j++];
tmp--;
}
arr[i] = sum;
}
}
else if(k<0)
{
k*=-1;
for(int i = 0;i<codeSize;i++)
{
int sum = 0;
int j = i-1;
int tmp = k;
while(tmp)
{
if(j<0)//连接数组尾
{
j = codeSize-1;
}
sum+=code[j--];
tmp--;
}
arr[i] = sum;
}
}
*returnSize = codeSize;
return arr;
}
2. 2058. 找出临界点之间的最小和最大距离 - 力扣(LeetCode)
//思路:将链表转为数组,再创建一个数组存储数组中临界点的下标,找到临界点的最小和最大距离再存储进一个新数组返回。
typedef struct ListNode LN;
int* nodesBetweenCriticalPoints(struct ListNode* head, int* returnSize)
{
LN* pmove = head;
int* ans = (int*)malloc(sizeof(int)*2);//答案数组
memset(ans,-1,sizeof(int)*2);
int* arr = (int*)malloc(sizeof(int)*100000);//存储链表的数组
int* cri = (int*)malloc(sizeof(int)*100000);//存储临界点下标的数组
int n = 0;
int count = 0;
int flag = 0;
int min = 1000000;
while(pmove)//将链表转为数组
{
arr[count++] = pmove->val;
pmove = pmove->next;
}
for(int i = 1;i<count-1;i++)
{
if((arr[i]>arr[i-1]&&arr[i]>arr[i+1])||(arr[i]<arr[i-1]&&arr[i]<arr[i+1]))//存储临界点下标
{
cri[n++] = i;
flag+=1;//判断临界点个数
}
}
for(int i = 0;i<n-1;i++)//找到临界点下标数组中距离的最小值
{
min = min<(cri[i+1]-cri[i])?min:(cri[i+1]-cri[i]);
}
if(flag>1)//如果临界点个数大>1,则有最大、最小距离
{
ans[0] = min;
ans[1] = cri[n-1]-cri[0];
}
*returnSize = 2;
return ans;
}
3. 2181. 合并零之间的节点 - 力扣(LeetCode)
//思路:暴力遍历 O(N^2)。遍历链表将0之间的数相加,存入新创建的链表中。
typedef struct ListNode LN;
struct ListNode* mergeNodes(struct ListNode* head)
{
LN* Sentry = (LN*)malloc(sizeof(LN));
LN* newhead = Sentry;
LN* pmove = head->next;
while(pmove&&pmove->next)
{
int sum = 0;
LN* newnode = (LN*)malloc(sizeof(LN));
newnode->next = NULL;
while(pmove->val!=0)//将0之间的数相加
{
sum+=pmove->val;
pmove = pmove->next;
}
newnode->val = sum;//存入新链表中
newhead->next = newnode;
newhead = newhead->next;
pmove = pmove->next;
}
return Sentry->next;
}