27. Remove Element

原题:
Given an array nums and a value val, 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.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two
elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

 Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five
 elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by 
the caller.
// using the length returned by your function, it prints the 
first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

翻译:
给你一个数组 nums和数val并就地删除数组中存在的所有传出数,并返回新的长度。
不要分配额外的数组空间, 你必须通过使用O(1)的额外内存修改输入数组来实现。

例 1:

Given nums = [3,2,2,3], val = 3,

你的函数需要返回length =  2, 而且nums前两个元素为2

你数组的长度可以超过返回的长度.

例 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

你的函数需要返回 length = 5, 而且前nums前五个 
元素包括 0, 1, 3, 0, 和 4 .
数组的前五个元素顺序可以随意

你数组的长度可以超过返回的长度.

解释:

为什么返回的值是整数,但您的答案是数组?

注意:输入数组是通过引用传入的,这意味着调用方也将知道对输入数组的修改。.

你可以这么认为:

// nums是通过引用传入的. (i.e., 不是通过复制)
int len = removeDuplicates(nums);

// 你在函数中对nums的任何修改调用者都会知道 

// 输出你返回长度的前几个元素 

for (int i = 0; i < len; i++) {
    print(nums[i]);
}

C程序

int removeElement(int* nums, int numsSize, int val){
    if(numsSize==0)return 0;
    int index = 0;
    for(int i=0;i<numsSize;++i)
    {
        if(nums[i]!=val)
        {
            nums[index]=nums[i];
            ++index;
        }
    }
    return index;
}

在这里插入图片描述
总结:
本题与26题类似,关键在于in-place算法的使用

在计算机科学中,一个原地算法(in-place algorithm)是一种使用小的,固定数量的额外之空间来转换资料的算法。当算法执行时,输入的资料通常会被要输出的部份覆盖掉。不是原地算法有时候称为非原地(not-in-place)或不得其所(out-of-place)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值