LeetCode | Remove Element(删除指定元素)

来源:互联网 发布:纸张分切软件 编辑:程序博客网 时间:2024/05/16 17:48


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.

删除数组中制定的元素,返回新的长度


题目解析

这道题和上一道题目很类似,也是遇到不合法的数据用后面的数据替换,不过这里的j不是从前往后遍历, 而是从后向前遍历,找到第一个不是关键字的数据放置到arr[i]的位置,然后i+1继续遍历。注意一些细节,比如输入的参数不合法(空指针,长度为零等情况),这道题目就不难了。

另:

也可以跟上一题一样,i和j都是从前向后遍历,当arr[j]的值和key的值不相等就对arr[i]进行赋值。

#include <stdio.h>#include <stdlib.h>int RemoveElement(int arr[],int len,int key);int main(){    int n,key;    int arr[20];    while(scanf("%d %d",&n,&key) != EOF){        for(int i = 0;i < n;++i)            scanf("%d",&arr[i]);        int len = RemoveElement(arr,n,key);        printf("len = %d\n",len);        for(int i = 0;i < len;++i){            printf("%d ",arr[i]);        }        putchar('\n');    }    return 0;}int RemoveElement(int arr[],int len,int key){    int i = 0,j = len-1;    if(arr == NULL || len <=0)        return 0;    while(i <= j){        if(arr[i] == key){            while(i<=j){                if(arr[j] != key)                    break;                --j;            }            if(i>j) //当最后的数据全部都是要删除的关键字的时候,会产生这样的情况                break;            arr[i] = arr[j];    //将后面的数据放置到要删除的数据的位置            --j;        }        ++i;    }    //最后返回的i的位置,不是合法的数据,从0--> i-1位置才是我们要求解的    return i;   //这时的返回值表示长度}



0 0
原创粉丝点击