美文网首页
27. Remove Element

27. Remove Element

作者: YellowLayne | 来源:发表于2017-06-15 09:48 被阅读0次

1.描述

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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3

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

2.分析

3.代码

int removeElement(int* nums, int numsSize, int val) {
    if (NULL == nums || 0 >= numsSize) return 0;
    unsigned int length = 0;
    for (unsigned int i = 0; i < numsSize; ++i) {
        if (nums[i] == val) continue;
        if (i != length) nums[length] = nums[i];
        ++length;
    }
    return length;
}

相关文章

网友评论

      本文标题:27. Remove Element

      本文链接:https://www.haomeiwen.com/subject/phsyqxtx.html