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

leetcode 283和2460

leetcode 283. Move Zeroes

代码:

class Solution {
public:void moveZeroes(vector<int>& nums) {int n = nums.size();int slowIdx = 0;for(int fastIdx = 0;fastIdx <n;fastIdx++){if(nums[fastIdx] != 0){nums[slowIdx++] = nums[fastIdx];}}while(slowIdx<n)nums[slowIdx++] = 0;}
};

其实可以更快

class Solution {
public:void moveZeroes(vector<int>& nums) {int n = nums.size();int i =0;for(int j =0;j <n;j++){if(nums[j] != 0){swap(nums[i++],nums[j]);}}}
};

leetcode 2460. Apply Operations to an Array

代码:

class Solution {
public:vector<int> applyOperations(vector<int>& nums) {int n = nums.size();for(int i = 0;i < n -1;i++){if(nums[i] == nums[i+1]){nums[i] *=2;nums[i+1] = 0;}}int slowIndex = 0;for(int firstIndex = 0;firstIndex < n;firstIndex++){if(nums[firstIndex] != 0){nums[slowIndex++] = nums[firstIndex];}}while(slowIndex < n)nums[slowIndex++] = 0;return nums;}
};

 更快的做法:

class Solution {
public:vector<int> applyOperations(vector<int>& nums) {int n = nums.size();for(int i = 0,j = 0;i < n;i++){if(i < n-1 && nums[i] == nums[i+1]){nums[i] *=2;nums[i+1] = 0;}if(nums[i]!=0)swap(nums[j++],nums[i]);}return nums;}
};

http://www.dtcms.com/a/157622.html

相关文章:

  • 【fork初体验】
  • 【2025 最新前沿 MCP 教程 03】基础构建模块:工具、资源与提示
  • 提取office最强悍的软件
  • 【白雪讲堂】
  • Python循环语句-while循环(基础语法,基础案例,嵌套应用,嵌套案例)
  • C++栈的模拟实现
  • Tableau 基础表制作
  • Qt Charts 绘制曲线图示例
  • Trae 宝藏功能实测:从 Mcp 搭建天气系统,到 AI 重塑 Excel 数据处理
  • C语言 函数递归
  • Eclipse 插件开发 4 工具栏
  • JAVA JVM面试题
  • 【TypeScript】速通篇
  • 比象AI创作系统,多模态大模型:问答分析+AI绘画+管理后台系统
  • ip-prefix前缀列表
  • 基于PyTorch的图像识别主要依赖于深度学习模型(尤其是卷积神经网络,CNN)对图像特征进行自动学习和分类
  • dubbo 异步化实践
  • Python类和对象四(十三)
  • 【springboot知识】配置方式实现SpringCloudGateway相关功能
  • 通过Golang实现快速实现MCP Server
  • Go 语言中的实时交互式编程环境
  • 量子跃迁:Vue组件安全工程的基因重组与生态免疫(完全体终局篇)
  • 正则表达式 工作案例
  • docker 常用配置
  • python 画折线统计图
  • Linux下的I/O复用技术之epoll
  • 模型 隐含前提
  • MyBatis缓存配置的完整示例,包含一级缓存、二级缓存、自定义缓存策略等核心场景,并附详细注释和总结表格
  • Python部署Docker报错:curl: (56) Recv failure: Connection reset by peer
  • 强化学习:高级策略梯度理论与优化方法