leetcode解题方案--027--Remove Element
2017-11-05 17:07
393 查看
题目
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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
分析
从前向后遍历数组,如果遇到相同的就将后面的元素复制过来。因此需要维持一个尾指针。class Solution { public int removeElement(int[] nums, int val) { int end = nums.length-1; int ans = 0; for (int i = 0; i<=end;i++) { if (nums[i] != val) { ans++; } else { while (end>i&&nums[end]==val) { end--; } if (nums[end]!=val) { nums[i] = nums[end]; end--; ans++; } } } return ans; } }
相关文章推荐
- leetcode解题方案--016--3 sum closest
- leetcode解题方案--075--Sort Colors
- leetcode解题方案--003--LongestSubstringWithoutRepeatingCharacters
- leetcode解题方案--004--MedianofTwoSortedArrays
- [LeetCode]题解(python):027-Remove Element
- leetcode解题方案--151--Reverse Words in a String
- leetcode解题方案--155--min stack
- leetcode解题方案--026--Remove Duplicates from Sorted Array
- leetcode解题方案--077--combinations
- LeetCode解题报告--Remove Element
- leetcode解题方案--078--subsets
- leetcode解题方案--039-- CombinationSum
- LeetCode 027 Remove Element
- leetcode解题方案--052-- N-Queens II
- leetcode解题方案--059--Spiral Matrix II
- leetcode解题报告(8):Remove Element
- leetcode解题方案--021--Merge Two Sorted Lists
- LeetCode-027 Remove Element
- leetcode解题集锦之 Remove Element
- [Leetcode] Duplicate Emails 我的解题方案