【leetcode】Remove Element

本文介绍了一种在数组中移除特定值并返回新长度的算法。提供了两种实现思路:一是通过交换元素并减少数组长度;二是使用一个指针记录合法元素的位置。附带C++及Java代码示例。

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.

 


题解:用一个len变量记录当前数组的长度。每次遇到元素elem,就把len-1指着的元素换到elem元素所在的地方,然后把len--。要注意的地方就是elem在数组结尾的时候,len减一减到和i相等的时候,就不能再减了,应该结束遍历,返回len的值。

代码如下:

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) {
 4         int len = n;
 5         for(int i = 0;i < len;i ++){
 6             if(A[i] == elem){
 7                 while(A[len - 1] == elem && len > i)
 8                     len--;
 9                 A[i] = A[len-1];
10                 if(len > i)
11                     len --;
12             }
13         }
14         /*for(int i= 0;i < len;i++)
15             cout <<A[i]<<endl;*/
16         return len;
17     }
18 };

 还有一种正序的想法,就是设置一个puthere指针,每次发现和elem不想等的元素,就放到puthere所指向的位置;

java代码如下:

 1 public class Solution {
 2     public int removeElement(int[] A, int elem) {
 3         int puthere = 0;
 4         int n = A.length;
 5         for(int i = 0;i < A.length;i++){
 6             if(A[i] != elem){
 7                 A[puthere] = A[i];
 8                 puthere++;
 9             }
10             else {
11                 n--;
12             }
13         }
14         return n;
15     }
16 }

 

转载于:https://www.cnblogs.com/sunshineatnoon/p/3778606.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值