【每日刷题】Day70

【每日刷题】Day70

🥕个人主页:开敲🍉

🔥所属专栏:每日刷题🍍

🌼文章目录🌼

[1. 922. 按奇偶排序数组 II - 力扣(LeetCode)](#1. 922. 按奇偶排序数组 II - 力扣(LeetCode))

[2. 905. 按奇偶排序数组 - 力扣(LeetCode)](#2. 905. 按奇偶排序数组 - 力扣(LeetCode))

[3. 515. 在每个树行中找最大值 - 力扣(LeetCode)](#3. 515. 在每个树行中找最大值 - 力扣(LeetCode))

1. 922. 按奇偶排序数组 II - 力扣(LeetCode)

//思路:归并。将数组中奇、偶数分别存储进两个数组,随后根据i的奇偶性从两个数组中拿取数据。

int* sortArrayByParityII(int* nums, int numsSize, int* returnSize)

{

int even[10001] = {0};//偶数数组

int count1 = 0;

int odd[10001] = {0};//奇数数组

int count2 = 0;

for(int i = 0;i<numsSize;i++)

{

if(nums[i]%2==0)

even[count1++] = nums[i];

else

odd[count2++] = nums[i];

}

int flag1 = 0;

int flag2 = 0;

for(int i = 0;i<numsSize;i++)

{

if(i%2==0)

nums[i] = even[flag1++];

else

nums[i] = odd[flag2++];

}

*returnSize = numsSize;

return nums;

}

2. 905. 按奇偶排序数组 - 力扣(LeetCode)

//思路:归并。与上一题类似。

int* sortArrayByParity(int* nums, int numsSize, int* returnSize)

{

int even[5002] = {0};

int count1 = 0;

int odd[5002] = {0};

int count2 = 0;

for(int i = 0;i<numsSize;i++)

{

if(nums[i]%2==0)

even[count1++] = nums[i];

else

odd[count2++] = nums[i];

}

int flag1 = 0;

int flag2 = 0;

while(flag1<count1)

{

nums[flag1] = even[flag1];

flag1++;

}

int begin = flag1;

while(flag2<count2)

{

nums[begin++] = odd[flag2];

flag2++;

}

*returnSize = numsSize;

return nums;

}

3. 515. 在每个树行中找最大值 - 力扣(LeetCode)

//思路:深度优先遍历。首先求出二叉树的最大深度,用于判断需要循环多少次。在每次循环中,我们让i的值作为我们所要求的第i层的最大值,采用深度优先遍历遍历到第i层,创建一个max变量,用于记录最大值,随后记录在答案数组中。

typedef struct TreeNode TN;

//判断是否为叶子结点

bool IsLeafNode(TN* root)

{

return !root->left&&!root->right;

}

//求二叉树最大深度

int TreeHigh(TN* root)

{

if(!root)

return 0;

if(IsLeafNode(root))

return 1;

int left = TreeHigh(root->left);

int right = TreeHigh(root->right);

return 1+(left>right?left:right);

}

//求第K层的最大值

void Max(TN* root,int k,int* max)

{

if(!root)

return;

if(k==1)//K==1说明当前层为所求层

{

(*max) = (*max)>(root->val)?(*max):root->val;//记录max,直接返回

return;

}

//深度优先遍历

Max(root->left,k-1,max);

Max(root->right,k-1,max);

}

int* largestValues(struct TreeNode* root, int* returnSize)

{

int* ans = (int*)malloc(sizeof(int)*10001);

int count = 0;

int high = TreeHigh(root);

for(int i = 1;i<=high;i++)//循环次数为要求层数

{

int max = -2147483648;

Max(root,i,&max);

ans[count++] = max;

}

*returnSize = count;

return ans;

}

相关推荐
2301_764441333 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI3 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly4 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives4 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1234 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
weixin_446023564 小时前
C语言:面向过程、应用底层开发、跨平台的通用程序设计语言
c语言·跨平台·数据类型·底层开发·面向过程
fengfuyao9855 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神6 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜6 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ06 小时前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习