当前位置:网站首页>力扣学习---0804
力扣学习---0804
2022-08-04 17:48:00 【young_man2】
一、移除元素
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
首先简单写一下我的思路,这道题目需要的是删除不存在的元素,其实也就是在原来的基础上将不需要的数据移动到数组的后面然后返回你需要的长度就行!
那么就可以使用双指针方式进行,走到对应的数据的位置的时候可以进行数据的交换,然后当两个指针碰撞的时候就可以结束了!

class Solution {
public int removeElement(int[] nums, int val) {
int length=nums.length;
if(length==0){
return 0;
}
int index=length-1;
//采用双指针的方式
for(int i=0;i<length;i++){
int prex=nums[i];
int last=nums[index];
if(prex==val){
nums[i]=nums[index];
i--;
index--;
}
if(i==index){
break;
}
}
return index+1;
}
}边栏推荐
猜你喜欢

OpenInfra Days China 2022 | SelectDB to share with you the Apache Doris in Internet advertising business practices

电源测试系统-ATE电源测试系统-ACDC电源模块测试系统NSAT-8000

使用scikit-learn计算文本TF-IDF值

Learning to Explore - Setting the Foreground Color for Fonts

【web自动化测试】Playwright快速入门,5分钟上手

.NET云原生应用发展论坛--8月7日邀你一起云上探索

Digital-intelligent supply chain management system for chemical manufacturing industry: build a smart supply system and empower enterprises to improve production efficiency

Investigation and Research Based on the Involution Behavior of College Students

DMPE-PEG-Mal,二肉豆蔻酰磷脂酰乙醇胺-聚乙二醇-马来酰亚胺简述

yarn detailed introductory tutorial
随机推荐
语音识别学习资源
Learning to Explore - Setting the Foreground Color for Fonts
arm交叉编译
OpenInfra Days China 2022 | SelectDB to share with you the Apache Doris in Internet advertising business practices
从-99打造Sentinel高可用集群限流中间件
荣耀互联对外开放,赋能智能硬件合作伙伴,促进全场景生态产品融合
R语言glm函数使用频数数据构建二分类logistic回归模型,分析的输入数据为频数数据(多个分类指标对应的阴性样本和阳性样本的频数数据)、weights参数指定频数值
LeetCode Question of the Day - 1403. Minimum Subsequence in Non-Increasing Order
PT100铂热电阻三种测温方法介绍
面试官:可以谈谈乐观锁和悲观锁吗
The second step through MySQL in four steps: MySQL index learning
Cholesterol-PEG-Maleimide,CLS-PEG-MAL,胆固醇-聚乙二醇-马来酰亚胺一种修饰性PEG
正则过滤字符串中 script 标签
The prefix and discretization
动态数组底层是如何实现的
下一代 AutoAI:从模型为中心,到数据为中心
2022年五一数学建模C题讲解
【技术笔记】树莓派4B开机流程整理(无显示器安装)
init和destory方法
php如何查询字符串以什么开头