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

Leetcode 150 | Day 1: Merge Sorted Array - Naive vs. Optimized

Angela F. 2026年06月02日 08:51 5 次阅读 来源:Dev.to

There's been no shortage of debate lately about whether grinding Leetcode still makes sense in the age of AI. I think it does. AI is a powerful tool, but it was built by humans; which means it inherited our strengths, our blind spots, and our biases. Leaning on it entirely without understanding what's happening under the hood is a risk. A mentor once told me: those who refuse to use AI are not hireable. But neither are those who rely on it entirely. Learning deeply is how you stay on the right side of that line. This is my journey into just that - learning deeply. Day 1 Leetcode 88: Merge Sorted Array This is an interesting problem. You begin with 4 pieces of data — 2 arrays and 2 integers: nums1 : a sorted array whose length equals nums1.length + nums2.length . The first m elements are valid numbers; the remaining indexes hold 0 s as placeholders. nums2 : a sorted array containing only valid numbers, with a length of n . m : the count of valid numbers in nums1. n : the count of valid numbers in nums2. The objective is to merge both arrays into sorted order in place . Since nums1 is already sized to hold every valid element from both arrays, it's where the final sorted result will live. Approach 1: Naive (Splice + Sort) This solution is 2 lines of code. That's it. It's a testament to how much ES6 advanced JavaScript. nums1 . splice ( m , n , ... nums2 ); nums1 . sort (( a , b ) => a - b ); Here's how it works. We start by calling .splice() on nums1. While .splice() has many use cases, here's what each argument is doing in this context: m : the index where we start deleting elements. Since m is the count of valid numbers in nums1, starting at index m puts us right at the first placeholder 0 — exactly where we want to be. n : the number of elements to delete. Since n equals the length of nums2, we're deleting exactly as many placeholders as we have values to insert. ...nums2 : the values we want to insert in place of the deleted elements. The ... is the spread operato

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