概述
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
public 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 27. Remove Element所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复