[LeetCode-27] Remove Element(数组元素删除)

来源:互联网 发布:java文件大小的单位 编辑:程序博客网 时间:2024/05/19 02:25

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.

【分析】数组中删掉元素,并且返回数组的长度

代码实现1:(从后面遍历至开头元素)

int removeElement(int* nums, int numsSize, int val){    if(!nums||numsSize <= 0)         return 0;    int countNum = numsSize-1; /*0->numsSize-1*/    int i = 0;    /*1.先处理1->numsSize-1个数据*/    while(countNum) {        if(*(nums+countNum) == val) {            for(i = countNum;i < numsSize-1;i++) {                *(nums+i) = *(nums+i+1);            }            numsSize = numsSize-1;        }        countNum--;    }    /*第一个数据*/    if(*nums == val) {        for(i = 0;i < numsSize-1;i++) {            *(nums+i) = *(nums+i+1);        }        numsSize = numsSize-1;    }    return numsSize;}

实现二:(从头开始遍历)

int removeElement(int* nums, int numsSize, int val){     if(!nums||numsSize <= 0)         return 0;     int i = 0;     int start = 0;     for(i = 0;i<numsSize;i++)     {        if(val != nums[i]) {            nums[start++] = nums[i];        }     }     return start;}
0 0
原创粉丝点击