977. Squares of a Sorted Array
Given an array of integers A
sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
1 | Input: [-4,-1,0,3,10] |
Example 2:
1 | Input: [-7,-3,2,3,11] |
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A
is sorted in non-decreasing order.
大概解释下题目:有序的有符号数组元素平方后排序。
方案一
思路:迭代循环每个元素进行平方,然后再用sort排序
1 | class Solution { |
result
Runtime: 124 ms, faster than 45.70% of C++ online submissions for Squares of a Sorted Array.
Memory Usage: 13.4 MB, less than 100.00% of C++ online submissions for Squares of a Sorted Array.
内存占用效果不错,但是执行效率就差了,for循环的原因?
方案二
新建一个数组替换原来的A
1 | class Solution { |
result
Runtime: 120 ms, faster than 58.11% of C++ online submissions for Squares of a Sorted Array.
Memory Usage: 13.5 MB, less than 99.64% of C++ online submissions for Squares of a Sorted Array.
效果并没有好多少。
方案三
读题不够仔细,原始数组就是有序的,只不过是包含了负数而已,这个排序就可以用来比较了,以下这个方案是讨论区的答案,有点巧妙。
1 | class Solution { |
result
Runtime: 100 ms, faster than 98.97% of C++ online submissions for Squares of a Sorted Array.
Memory Usage: 13.3 MB, less than 100.00% of C++ online submissions for Squares of a Sorted Array.
执行效率和内存占用表现都相当好;
tip
后续类似循环的题目,最高的效率就是要在同一个循环里面,把多件事同时做了。