当前位置: 首页 > 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
  • 榆林市委常委王华胜已任榆林市政协党组书记
  • 最高法专门规范涉企案件审执工作:从源头防止趋利性执法司法
  • 女儿被偷拍后,一个父亲的战斗
  • 蜀道考古调查阶段性成果发布,新发现文物遗存297处
  • 财政部:前3月国有企业利润总额10907.4亿元,同比增1.7%
  • 冯象|那“交出”后的崩溃,如撒旦坠落诸天