今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Leetcode 150 | Day 2: Remove Element - Naive vs. Optimized

Angela F. 2026年06月04日 08:52 3 次阅读 来源:Dev.to

Leetcode 27: Remove Element Leetcode 27 asks us to remove a specific value from an array. The value to be removed is passed in as a parameter to the function along with the array. Just as we did in Day 1, we will cover a naive approach and an optimized approach and discuss the trade-offs between them. I think in the end there's a pretty clear winner. Let's get started. For both approaches we will use the following values: nums = [1, 3, 3, 2, 4] val = 3 Approach 1: Naive (For Loop + Splice) This approach uses a for loop and leverages .splice() for removals. Solution: var removeElement = function ( nums , val ) { let k = 0 ; for ( let i = 0 ; i < nums . length ; i ++ ) { if ( nums [ i ] === val ) { nums . splice ( i , 1 ); i -- ; } else { k ++ ; } } return k ; }; We begin by initializing a variable k to 0. We then enter the for loop. The condition is standard: create a variable i initialized to 0, continue looping while i is less than nums.length to avoid going past the end of the array, and increment by 1 each time through. Each iteration checks one condition: whether nums[i] is equal to val . If true, we call .splice() on the array. The arguments we pass to splice are i and 1 . i is the index at which we want to start removing, and 1 tells splice to remove only that one element. We then decrement i . The reason for this took me some time to wrap my brain around, so I have included a visual below to make it concrete. The core issue is this: when splice removes an element, every element to the right shifts one index to the left. Without i-- , the loop would increment i on the next iteration and skip right over the element that just shifted in. i-- counteracts that by stepping i back, so after the loop increments it, i lands exactly where the shifted element now sits. If nums[i] !== val , we skip the splice and increment k instead. At the end we return k , which holds the count of elements remaining after all occurrences of val have been removed. Time complexity: O(n²)

本文内容来源于互联网,版权归原作者所有
查看原文