leetcode 27. Remove Element(C语言,快速排序思想,剔除数组中与目标值相等的数)20

本文介绍了一种基于快速排序思想的算法,用于从数组中移除特定值的所有实例,并返回处理后数组的有效长度。该算法在原地操作,不使用额外空间,符合常量内存约束条件。

贴原题:

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.

解析:
  本题是给出一个数组和一个目标值,让把数组中与目标值相等的数都剔除,并返回剔除后的数组的大小。
  我利用了快速排序的思想,我之前在写另一道leecode的时候便自己写过快速排序,那么写这道题的时候自然是轻车驾熟。我只要把与目标值相等的数排序到数组的最后,然后返回不与目标值相等的数量便可以了。
  贴出我之前写的快速排序算法:
  http://blog.youkuaiyun.com/m0_37454852/article/details/78067025
  http://blog.youkuaiyun.com/m0_37454852/article/details/78062540

贴代码:

int removeElement(int* nums, int numsSize, int val) {
    if(!numsSize)//空数组则直接返回0
    {
        return 0;
    }
    int i=0, j=numsSize-1;
    while(i!=j)
    {
        if(*(nums+i)==val)//若该数与目标值相等,则交换该数与最后一位
        {
            int temp=*(nums+i);
            *(nums+i)=*(nums+j);
            *(nums+j)=temp;
            j--;//使最后一位前进一步
        }
        else//否则继续判断下一个数
        {
            i++;
        }
    }
    //跳出循环后,j之前的数都!=val,其后的数都==val
    if(*(nums+j)==val)//判断最后的那一位数
    {
        j--;
    }
    return j+1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值