[Leetcode] remove element 删除元素
2024-08-28 10:02:39
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
题意:删除给定的数,然后返回新的长度。
思路:这题的思路和sort colors差不多,是其简化版。大致的思路是:使用两个指针,指针l 指前,指针 r 指后,遍历数组,遇到给定的数,则将指针 l 指向的元素和r指向的元素交换,每交换一次r--一次,然后重新从指针l处重新遍历;若不是给定的数,则直接跳过即可。代码如下:
class Solution {
public:
int removeElement(int A[], int n, int elem)
{
int count=;
if(n<) return ;
int l=,r=n-;
while(l<=r)
{
if(A[l]==elem)
{
swap(A[l],A[r])
r--;
count++;
}
else
l++;
}
return n-count;
}
};
思路二:从前向后遍历数组,遇到给定数,记下其位置,将其和后面第一个不为给定数交换,即可。代码如下:
class Solution
{
public:
int removeElement(int A[],int n,int elem)
{
int count=;
for(int i=;i<n;++i)
{
if(A[i]==elem)
count++;
else if(count>) //避免多个连续
A[i-count]=A[i];
}
return n-count;
}
}
最新文章
- Power of Four(Difficulty: Easy)
- java 求 两个数的百分比% (转)
- jsp页面中的java代码
- 使用 Entity Framework
- xilinx cpld XC95144XL 最小系统板
- COJ 3012 LZJ的问题 (有向图判环)
- js关闭 window.open 打开的页面
- HTML系列(五):超链接
- 第4章 同步控制 Synchronization ----事件(Event Objects)
- 前端基于Canvas生成等值面的方案
- Java——static关键字
- Node url模块
- pycharm2016.2.3注册码到期, 激活, 破解版
- Linux下的反调试技术
- Is there a way to detect if call is in progress? Phone Event
- 第二十四章 springboot注入servlet
- 使用HVTableView动态展开tableView中的cell
- SpringBoot实战(六)之使用LDAP验证用户
- 最大流算法-ISAP
- 集合的addAll方法--list.addAll(null)会报错--java.lang.NullPointerException