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

【LeetCode 热题 100】只出现一次的数字 / 多数元素 / 颜色分类 / 寻找重复数

头像
⭐️个人主页:@小羊
⭐️所属专栏:LeetCode 热题 100
很荣幸您能阅读我的文章,诚请评论指点,欢迎欢迎 ~

动图描述

目录

    • 只出现一次的数字
    • 多数元素
    • 颜色分类
    • 下一个排列
    • 寻找重复数


只出现一次的数字

  • 只出现一次的数字

在这里插入图片描述

class Solution {
public:int singleNumber(vector<int>& nums) {int res = 0;for (auto e : nums) res ^= e;return res;}
};

多数元素

  • 多数元素

在这里插入图片描述

常规哈希表。

class Solution {
public:int majorityElement(vector<int>& nums) {unordered_map<int, int> hashmap;int n = nums.size() / 2;int target = 0;for (auto e : nums){if (++hashmap[e] > n){target = e;break;}}return target;}
};

投票法。

class Solution {
public:int majorityElement(vector<int>& nums) {int target = 0, cnt = 0;for (auto e : nums){if (e == target) cnt++;else if (--cnt < 0){target = e;cnt = 1;}}return target;}
};

颜色分类

  • 颜色分类

在这里插入图片描述

class Solution {
public:void sortColors(vector<int>& nums) {int l = -1, r = nums.size(), i = 0;while (i < r){if (nums[i] == 0) swap(nums[++l], nums[i++]);else if (nums[i] == 1) i++;else swap(nums[--r], nums[i]);}}
};

下一个排列

  • 下一个排列

在这里插入图片描述

class Solution {
public:void nextPermutation(vector<int>& nums) {int i = nums.size() - 2;while (i >= 0 && nums[i] >= nums[i + 1]) i--;if (i >= 0){int j = nums.size() - 1;while (j >= 0 && nums[i] >= nums[j]) j--;swap(nums[i], nums[j]);}reverse(nums.begin() + i + 1, nums.end());}
};

寻找重复数

  • 寻找重复数

在这里插入图片描述

class Solution {
public:int findDuplicate(vector<int>& nums) {int fast = 0, slow = 0;do{slow = nums[slow];fast = nums[nums[fast]];} while (fast != slow);slow = 0;while (fast != slow){slow = nums[slow];fast = nums[fast];}return slow;}
};

本篇文章的分享就到这里了,如果您觉得在本文有所收获,还请留下您的三连支持哦~

头像
http://www.xdnf.cn/news/985285.html

相关文章:

  • 建造者模式(Builder Pattern)
  • 设计模式-组合模式
  • Ubuntu20.04更新Cmake版本
  • 找到字符串中所有字母异位词
  • 使用 PyTorch 和 TensorBoard 实时可视化模型训练
  • SpringBoot学习day1-SpringBoot的简介与搭建
  • Phthon3 学习记录-0611
  • Windows 删除文件出现错误代码0x80070570:文件或目录损坏且无法读取
  • 第五章网络管理
  • vibe coding 2025工具全景图
  • 构建高效开发节奏:我的IDEA休息提醒插件实践
  • fastadmin自动保存格式datetime
  • JavaEE-SpringBoot
  • 基于SpringBoot实现的课程答疑系统设计与实现【源码+文档】
  • 【MySQL数据库 | 第四篇】 数据类型+DDL表操作1
  • 从零开始了解数据采集技术篇(2)——如何提高数据采集的精度与速度
  • ALIGN_COMMA_ENABLE参数
  • 贪心选择 (Greedy Choice)
  • 大语言模型智能体开发的技术框架与应用前景
  • 日期的数据格式转换
  • 红队手法:从web漏洞到ssh横向移动 实战方案
  • vue3笔记(1)自用
  • 选择、填空、判断
  • 深入理解Python协程:async def、async for、await、yield详解
  • 学习日记-day27-6.11
  • Debian/Ubuntu systemd coredump调试程序Crash
  • 光纤传感预警工业罐体爆炸风险
  • 6.11打卡
  • PyTorch:让你的深度学习从「纸上谈兵」到「真枪实战」的魔法棒!
  • 直接使用阿里云OSS的地址,报跨域访问的问题怎么解决