我是靠谱客的博主 个性草丛,这篇文章主要介绍LeetCode 27. Remove Element,现在分享给大家,希望可以做个参考。

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
16
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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(40)

评论列表共有 0 条评论

立即
投稿
返回
顶部