977:有序数组的平方

This commit is contained in:
huangge1199@hotmail.com 2021-07-08 22:59:03 +08:00
parent adccc07d61
commit 7765c3b22c
2 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,66 @@
//给你一个按 非递减顺序 排序的整数数组 nums返回 每个数字的平方 组成的新数组要求也按 非递减顺序 排序
//
//
//
//
//
//
// 示例 1
//
//
//输入nums = [-4,-1,0,3,10]
//输出[0,1,9,16,100]
//解释平方后数组变为 [16,1,0,9,100]
//排序后数组变为 [0,1,9,16,100]
//
// 示例 2
//
//
//输入nums = [-7,-3,2,3,11]
//输出[4,9,9,49,121]
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 104
// -104 <= nums[i] <= 104
// nums 已按 非递减顺序 排序
//
//
//
//
// 进阶
//
//
// 请你设计时间复杂度为 O(n) 的算法解决本问题
//
// Related Topics 数组 双指针 排序
// 👍 247 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
//977:有序数组的平方
class SquaresOfASortedArray{
public static void main(String[] args) {
//测试代码
Solution solution = new SquaresOfASortedArray().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] sortedSquares(int[] nums) {
for (int i = 0; i < nums.length; i++) {
nums[i]*=nums[i];
}
Arrays.sort(nums);
return nums;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p>给你一个按 <strong>非递减顺序</strong> 排序的整数数组 <code>nums</code>,返回 <strong>每个数字的平方</strong> 组成的新数组,要求也按 <strong>非递减顺序</strong> 排序。</p>
<ul>
</ul>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums = [-4,-1,0,3,10]
<strong>输出:</strong>[0,1,9,16,100]
<strong>解释:</strong>平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums = [-7,-3,2,3,11]
<strong>输出:</strong>[4,9,9,49,121]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code><span>1 <= nums.length <= </span>10<sup>4</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>nums</code> 已按 <strong>非递减顺序</strong> 排序</li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>请你<span style="color: rgb(36, 41, 46); font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Helvetica, Arial, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">设计时间复杂度为 <code>O(n)</code> 的算法解决本问题</span></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>双指针</li><li>排序</li></div></div>\n<div><li>👍 247</li><li>👎 0</li></div>