Leetcode 27. Remove Element
2017-01-26 10:25
459 查看
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.
s思路:
1. 思路和26.Remove Duplicates from Sorted Array一样。仍然是two pointer.
2. 区别就是,两个指针都从最右边往左移动,用右指针到array的最右端之间的subarray来存放等于val的值。
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.
s思路:
1. 思路和26.Remove Duplicates from Sorted Array一样。仍然是two pointer.
2. 区别就是,两个指针都从最右边往左移动,用右指针到array的最右端之间的subarray来存放等于val的值。
//two pointer class Solution { public: int removeElement(vector<int>& nums, int val) { // int n=nums.size(); int right=n-1; for(int left=n-1;left>=0;left--){ if(nums[left]==val){ nums[left]=nums[right]; nums[right]=val; right--; } } return right+1; } };
相关文章推荐
- leetcode-27-Remove Element
- 【LeetCode】27. Remove Element
- LeetCode | 27. Remove Element
- LeetCode 27:Remove Element
- leetcode——27——Remove Element
- LeetCode 27. Remove Element
- LeetCode 27---Remove Element
- leetcode27: Remove Element
- 刷题的日常[Leetcode]——27)Remove Element
- leetcode[27]:Remove Element
- leetcode 27: Remove Element
- LeetCode 27 - Remove Element
- LeetCode 27. Remove Element
- Leetcode 27 Remove Element
- LeetCode------27. Remove Element
- leetcode27 Remove Element
- 【LeetCode】C# 27、Remove Element
- leetcode 27. Remove Element
- [Leetcode] 27 - Remove Element
- leetcode 27 Remove Element