27. Remove Element 解题记录

题目描述:

Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

本题的要求是:给我们一个数和数组,让我们移除数组中的这个数并返回新数组的长度。而且不能分配新的空间给数组,超出数组长度还有数是没有关系的。(例:要求返回的是{2,3},但返回的是{2,3,1}也是无所谓的)。

例子:

1 Given nums = [3,2,2,3], val = 3,
2 
3 Your function should return length = 2, with the first two elements of nums being 2.

 

解题思路:

这题的思路比较简单,只要将数组中的数与要求移除的数进行逐一比较,将不同的数移到数组前面覆盖相同的数即可。

代码:

1 int removeElement(int* nums, int numsSize, int val) {
2     int count=0;
3     for(int i=0;i<numsSize;i++){
4         if(nums[i]!=val){
5             nums[count++]=nums[i];
6         }
7     }
8     return count;
9 }

 

转载于:https://www.cnblogs.com/sakuya0000/p/8398040.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值