leetcode 27. Remove Element(C语言,快速排序思想,剔除数组中与目标值相等的数)20
2017-10-02 11:21
756 查看
贴原题:、
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.csdn.net/m0_37454852/article/details/78067025
http://blog.csdn.net/m0_37454852/article/details/78062540
贴代码:
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.csdn.net/m0_37454852/article/details/78067025
http://blog.csdn.net/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; }
相关文章推荐
- leetcode 27 Remove Element(移除数组中的与val相等的元素)
- LeetCode_Easy心得:27. Remove Element(C语言)
- LeetCode Remove Element 快速删除数组中的某一值
- Leetcode27:Remove Element(移除数组中指定的元素)
- 27. Remove Element(移除数组中与指定值相等的元素)
- [C++]LeetCode 27: Remove Element(删除数组中指定元素)
- [leetcode]-27. Remove Element(C语言)
- LeetCode - 26/80/27/283 - Remove/Move Element from Array
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- 每日一练之Remove Element【LeetCode No.27】—删除数组相应值
- Leetcode:27. Remove Element(JAVA)
- Leetcode 27. Remove Element (Easy) (java)
- C语言数组--快速排序
- 【LeetCode】27. Remove Element(移除元素)
- LeetCode 27. Remove Element(java)
- [Leetcode]Leetcode 27:Remove Element
- 【LEETCODE】27-Remove Element
- leetcode 26. Remove Duplicates from Sorted Array从排序数组中移出重复元素(双指针)
- leetCode 27.Remove Element (删除元素) 解题思路和方法