Description:
Given an array nums and a value val, 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.
Solution:
和上一题26类似
这种可以称为双指针,一个指向当前遍历的值,一个指向数组待放入的位置,只需要走一遍,速度很快。所以用时0ms,打败了100% JAVA submissions
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public int removeElement(int[] nums, int val) { if(nums.length == 0) return 0; int count = 0; int cur = 0; int i = 0; while(i < nums.length){ if(nums[i] != val){ count++; nums[cur++] = nums[i]; } ++i; } return count; }
最后
以上就是个性草丛最近收集整理的关于LeetCode 27. Remove Element的全部内容,更多相关LeetCode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复