当前位置: 首页 > 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;}
};

相关文章:

  • 【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
  • 强制性国家标准《危险化学品企业安全生产标准化通用规范》发布
  • 抗美援朝老战士宁昭逝世,享年93岁
  • 五一“大车流”来了,今日午后G40沪陕高速开始迎来出沪高峰
  • 海口市政协党组成员、秘书长、机关党组书记汪娟被查
  • 复星医药换帅:陈玉卿接棒吴以芳任董事长,吴以芳改任复星国际执行总裁
  • 绿地控股:今年一季度营业收入356亿元,中高层管理人员带头降薪