尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

LeetCode 27. Remove Element

LeetCode 27. Remove Element 题目Given an arraynumsand a valueval, 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 bymodifying the input array in-placewith O(1) extra memory.The order of elements can be changed. It doesnt matter what you leave beyond the new length.Example 1:Given nums [3,2,2,3], val 3, Your function should return length 2, with the first two elements of nums being 2. It doesnt matter what you leave beyond the returned length.Example 2:Givennums[0,1,2,2,3,0,4,2],val2, Your function should return length 5, with the first five elements ofnumscontaining0,1,3,0, and4. Note that the order of those five elements can be arbitrary. It doesnt matter what values are set beyond the returned length.Clarification:Confused why the returned value is an integer but your answer is an array?Note that the input array is passed in byreference, which means modification to the input array will be known to the caller as well.Internally you can think of this:// nums is passed in by reference. (i.e., without making a copy) int len removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i 0; i len; i) { print(nums[i]); }这道题完全就是昨天的Remove Duplicates from Sorted Array的翻版上来的思路马上就是快慢指针一想觉得没问题一试还是觉得没问题就快乐提交了时间复杂度O(n)空间复杂度O(1)运行时间0ms代码如下class Solution { public: int removeElement(vectorint nums, int val) { int i 0; for (int j 0; j nums.size(); j) { if (nums[j] ! val) { nums[i] nums[j]; i; } } return i; } };然后看了solutions发现有一个改进版本思路来源于如果遇到了[1, 2, 3, 4, 5]而我们要移除4那么我们需要对1、2、3都进行一次冗余的赋值。为了消除这种冗余由于题目说了元素的顺序可以改变那么可以在每次遇到需要删除的元素时把这个元素和数组最后一个元素进行交换这样每次遇到需要删除的都能减少数组的size。代码运行时间4msclass Solution { public: int removeElement(vectorint nums, int val) { int i 0; int n nums.size(); while (i n) { if (nums[i] val) { nums[i] nums[n - 1]; n--; } else { i; } } return i; } };2022.10.22这道题还是想了一下才写出来可能刚开始被绕进去了。还是快慢指针这次因为要remove某个特定值所以这个值可能出现在第一个所以fast和slow都从0开始。当fast val的时候不保留fast直接让fast当fast ! val的时候当前的slow应该是当前的fast并让slow和fast都。也是交完回来才发现可以简化写法但逻辑没有那么直观。class Solution { public int removeElement(int[] nums, int val) { int len nums.length; if (len 0) { return len; } int slow 0; int fast 0; while (fast len) { // option 1 if (nums[fast] ! val) { nums[slow] nums[fast]; slow; fast; } else { fast; } // option 2: improvement /* if (nums[fast] ! val) { nums[slow] nums[fast]; slow; } fast; */ } return slow; } }2026.8.19因为刚刚写了2460所以这个相当于是那个的subset就一遍过了。想清楚了其实挺简单的nonVal表示这个和这个之前都不等于val另一个遍历整个数组。如果遍历的不等于val就把nonVal变成遍历那个。因为剩下的元素都不用管所以遍历完直接return就行。class Solution { public int removeElement(int[] nums, int val) { int nonVal 0; // this and before this are non val int i 0; while (i nums.length) { if (nums[i] ! val) { nums[nonVal] nums[i]; nonVal; } i; } return nonVal; } }
返回列表