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

推荐订阅源

罗磊的独立博客
小众软件
小众软件
The Cloudflare Blog
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
S
SegmentFault 最新的问题
宝玉的分享
宝玉的分享
博客园 - 叶小钗
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research
T
Tailwind CSS Blog
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
Y
Y Combinator Blog
D
Docker
Microsoft Azure Blog
Microsoft Azure Blog

博客园 - 司徒正美

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;
};