LeetCode:Remove Element(删除数组中的特定元素)
2015-02-03 15:45
351 查看
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:一次遍历,遍历过程中如果遇到需要删除的元素,就将此位置的元素与数组末端元素交换。
方法2:使用双指针解决,在快指针遍历数组的过程中,如果当前元素不等于需要删除的元素,则将此元素复制到慢指针所指位置。
两种方法的时间复杂度均是O(n),方法1适用于数组中需要删除的元素较少的情况,而方法2适用于数组中需要删除的元素较多的情况。
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
方法1:一次遍历,遍历过程中如果遇到需要删除的元素,就将此位置的元素与数组末端元素交换。
class Solution { public: int removeElement(int A[], int n, int elem) { if(A==NULL || n<1) return 0; int i=0; while(i<n){ if(A[i]==elem) //swap(A[i],A[--n]);可以不理会末端的值,将swap优化为直接赋值 A[i] = A[--n]; else ++i; } return n; } };
方法2:使用双指针解决,在快指针遍历数组的过程中,如果当前元素不等于需要删除的元素,则将此元素复制到慢指针所指位置。
class Solution { public: int removeElement(int A[], int n, int elem) { if(A==NULL || n<1) return 0; int slow = -1, fast = -1; while(++fast<n){ if(A[fast]!=elem) A[++slow] = A[fast]; } return slow+1; } };
两种方法的时间复杂度均是O(n),方法1适用于数组中需要删除的元素较少的情况,而方法2适用于数组中需要删除的元素较多的情况。
相关文章推荐
- [C++]LeetCode 27: Remove Element(删除数组中指定元素)
- leetcode:26&80 Remove Duplicates from Sorted Array 删除数组中的重复元素
- leetCode 27.Remove Element (删除元素) 解题思路和方法
- LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2
- leetcode:Remove Element删除元素
- 每日一练之Remove Element【LeetCode No.27】—删除数组相应值
- LeetCode Remove Element 快速删除数组中的某一值
- leetCode 27.Remove Element (删除元素) 解题思路和方法
- LeetCode | Remove Duplicates from Sorted Array(删除有序数组的重复元素)
- Leetcode刷题记——26. Remove Duplicates from Sorted Array(删除数组重复元素)
- leetcode 27 Remove Element(移除数组中的与val相等的元素)
- Leetcode27:Remove Element(移除数组中指定的元素)
- leetcode:Remove Element (删除给定元素)【面试算法题】
- Remove Element 数组中删除给定元素 @ LeetCode
- [Leetcode] Remove duplicates from sorted array 从已排序的数组中删除重复元素
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- LeetCode 27. Remove Element(删除元素)
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- leetcode:Remove Duplicates from Sorted Array去掉排序数组中重复的元素