[C语言][LeetCode][27]Remove Element

题目

Remove Element
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.

标签

Array、Two Pointers

难度

简单

分析

题目意思是给定一个整形数组nums,传入一个整形val,删除数组里与val相同的值。我这里malloc一个新的数组array,然后逐个比较nums数组与val的值,不相同的值,就存放在array,然后将array重新覆盖nums。

C代码实现

int removeElement(int* nums, int numsSize, int val) {
    int i = 0, j = 0;

    int *array = (int *)malloc(sizeof(int)*numsSize);

    for(i=0; i<numsSize; i++)
    {
        if(val != nums[i])
        {
            array[j] = nums[i];
            j++;
        }
    }

    for(i=0; i<j; i++)
        nums[i] = array[i];

    free(array);

    return j;
}

你可能感兴趣的:(LeetCode)