当前位置: 首页 > news >正文

C语言 | Leecode C语言题解之第229题多数元素II

题目:

题解:

/*** Note: The returned array must be malloced, assume caller calls free().*//*假定 num1,num2 为出现次数大于 nums.length / 3 的两个数。(最多出现两个)遍历 nums, 若出现 num1、num2 中任意一数,计数+1,若都不等,则计数-1.若 num1、num2 有一个计数 < 0,则替换成当前遍历数(更换新的众数)数组可能出现 无众数 或只有 一众数 情况,所以需要再次遍历数组,统计所选众数出现次数,将满足条件(出现次数大于 nums.length / 3 )的数加入返回集合。
*/int* majorityElement(int* nums, int numsSize, int* returnSize){int *arr = NULL;int can1, can2;int cnt1 = 0, cnt2 = 0;int i;if (nums == NULL || numsSize <= 1) {*returnSize = numsSize;return nums;} can1 = nums[0];can2 = nums[1];for (i = 0; i < numsSize; i++) {if (nums[i] == can1) {cnt1++;continue;} else if (nums[i] == can2) {cnt2++;continue;} else {cnt1--;cnt2--;}/* 保证每次只替换一个数据 */if (cnt1 < 0) {can1 = nums[i];cnt1 = 1;cnt2++;}if (cnt2 < 0) {can2 = nums[i];cnt2 = 1;cnt1++;}            }cnt1 = 0;cnt2 = 0;for (i = 0; i < numsSize; i++) {if (nums[i] == can1)  {cnt1++;} else if (nums[i] == can2) {cnt2++;}}arr = (int *)malloc(sizeof(int) * 2);*returnSize = 0;i = 0;if (cnt1 > numsSize / 3) {arr[i++] = can1;*returnSize += 1;}if (cnt2 > numsSize / 3) {arr[i++] = can2;*returnSize += 1;}return arr;
}
http://www.lryc.cn/news/400811.html

相关文章:

  • mybatis-plus映射mysql的json类型的字段
  • 20240716 Codeforces题目
  • 29.【C语言】自定义函数
  • C++面向对象编程 基础篇(3)函数基础
  • excel有条件提取单元格特定文本(筛选纯文字的单元格或含有数字的单元格、单元格提取不同的文本长度)
  • HBase 在统一内容平台业务的优化实践
  • 【异常解决】Unable to start embedded Tomcat Nacos 启动报错
  • 【Java面向对象】对象和类
  • 在微服务架构架构中父工程中的`<dependencyManagement>`和 `<dependencies>`的区别
  • Docker安装Zookeeper、RocketMQ
  • Ubuntu 磁盘扩容
  • 如何在QGC中接收和处理无人机上传的各种传感器数据(如GPS、IMU等)。
  • Spring配置Bean自己的关系:继承和依赖
  • 科技与狠活
  • Vue:axios请求数据转存leanCloud
  • 实战篇(九):解锁3D魔方的秘密:用Processing编程实现交互式魔方
  • Android系统上常见的性能优化工具
  • TG创建小程序交互APP登录以及机器人信息
  • 探索大模型能力--prompt工程
  • 【经验分享】运用云服务器实现挂机手机网课的操作,部分手机软件适用
  • 【从0到1进阶Redis】主从复制 — 主从机宕机测试
  • Flask启动5000端口后关不掉了?
  • Redis的热key解决
  • 在linux中查找 / 目录下的以.jar结尾的文件(find / -name *.jar)
  • 【Python爬虫教程】第6篇-使用session发起请求
  • 【Hot100】LeetCode—763. 划分字母区间
  • 分布式服务基于Zookeeper的分布式锁的实现
  • Rust编程-I/O
  • FastAPI 学习之路(四十七)WebSockets(三)登录后才可以聊天
  • 数据结构—链式二叉树-C语言