惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Martin Fowler
Martin Fowler
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
C
Check Point Blog
H
Help Net Security
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
P
Proofpoint News Feed
V
Visual Studio Blog
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
S
SegmentFault 最新的问题
L
LangChain Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
有赞技术团队
有赞技术团队
博客园_首页
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏

博客园 - 司徒正美

leetcode 91. Decode Ways leetcode 1214 Two Sum BSTs leetcode 213 House Robber II leetcode 198 House Robber I leetcode 986. Interval List Intersections leetcode 869. Reordered Power of 2 leetcode 925. Long Pressed Name leetcode 457. Circular Array Loop leetcode 1093. Statistics from a Large Sample leetcode 881. Boats to Save People leetcode 844. Backspace String Compare leetcode 1032. Stream of Characters leetcode 1023. Camelcase Matching leetcode 745 Prefix and Suffix Search leetcode 720. Longest Word in Dictionary leetcode 692. Top K Frequent Words leetcode 677. Map Sum Pairs leetcode 676. Implement Magic Dictionary leetcode 648. Replace Words
leetcode 977. Squares of a Sorted Array
司徒正美 · 2020-01-02 · via 博客园 - 司徒正美

比较直观的解法

var sortedSquares = function(A) {
   return A.sort((a, b)=>{
        return Math.abs(a) -Math.abs(b)
    }).map(function(el){
       return el * el
   })
};

另一个,从左右两端开始比较,可能是-123与124比较,然后是-123与122

var sortedSquares = function(A) {
    let left = 0;
    let right = A.length - 1;
    const result = new Array(A.length);
    let index = A.length - 1;
    while (left <= right) {
        const leftSquare = A[left] * A[left];
        const rightSquare = A[right] * A[right];
        if (leftSquare > rightSquare) {
            result[index] = leftSquare;
            left++;
        } else {
            result[index] = rightSquare;
            right--;
        }
        index--;
    }
    return result;
};