贴原题:、
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;
}