LeetCode: Squares of a Sorted Array Solution
Map and sort or vice versaImplementation: Array Manipulation
1var sortedSquares = function (nums) {2 return nums.map(num => num * num).sort((a, b) => a - b)3}
Implementation: Two Pointers
1var sortedSquares = function (nums) {2 const powOf2 = x => x ** 234 const n = nums.length5 let lo = 06 let hi = n - 17 const res = []89 while (lo <= hi) {10 const a = powOf2(nums[lo])11 const b = powOf2(nums[hi])12 if (a < b) {13 res.push(b)14 hi--15 } else {16 res.push(a)17 lo++18 }19 }2021 return res.reverse()22}
Comments
Loading comments...
Tags
leetcode
array
two pointers
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Previous Post
Codility: MaxNonoverlappingSegments
Lesson 16 Greedy Algorithms