LeetCode题解之Squares of a Sorted Array 1、题目描述 2、问题分析 使用过两个计数器。 3、代码 1 class Solution { 2 public: 3 vector<int> sortedSquares(vector<int>& A) { 4 int left = 0, right = A.size() - 1; 5 vector<int> res; 6 while (left <= right) { 7 if (abs(A[...
给你一个包括正数和负数的有序数组,让你返回每个数字的乘积组成的有序数组。 虽然是个easy的题目,我觉得还是用到技巧了的,值得记录一下。 二.思路 用了三个下标变量: 一个用来保存新的乘积; 另外两个用来从数组的开头和末尾 分别遍历。 代码: class Solution { public int[] sortedSquares(int[] A) { int...
题目要求 Given an array of integersAsorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 题目分析及思路 题目给出一个整数数组,已经按照非减顺序排列好了。要求返回一个数组,包含的元素是已知数组元素的平方,且按照非减顺序排列。可以使用列...
class Solution { public: vector<int> sortedSquares(vector<int>& A) { vector<int> a; for(int i=0; i<A.size(); i++){ a.push_back(A[i] * A[i]); } for(int i=1; i 0 && temp < a[j-1]){ a[j] = a[j-1]; j--; } a[j] = temp; } return a; } };编辑于 20...
假设有两个指针,分别从头和从尾向中间移动,然后比较左右两个值的绝对值大小,绝对值大的将平方和添加到最左边,一直到两个指针相遇。 class Solution:def sortedSquares(self, A):answer = [0] * len(A)l, r = 0, len(A) - 1while l <= r:left, right = abs(A[l]), abs(A[r])if left > ...
977. Squares of a Sorted Array* 977. Squares of a Sorted Array* https://leetcode.com/problems/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......
Input:[-4,-1,0,3,10] Output:[0,1,9,16,100] 1. 2. Example 2: Input:[-7,-3,2,3,11] Output:[4,9,9,49,121] 1. 2. 1classSolution {2publicint[] sortedSquares(int[] A) {3intn =A.length;4int[] result =newint[n];5inti =0, j = n -1;6for(intp = n -1; p ...
977. Squares of a Sorted Array Given an integer arraynumssorted in non-decreasing order, returnan array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100]...
给你一个按非递减顺序排序的整数数组nums,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 示例1: 输入:nums = [-4,-1,0,3,10]输出:[0,1,9,16,100]解释:平方后,数组变为 [16,1,0,9,100] 排序后,数组变为 [0,1,9,16,100] ...
977. Squares of a Sorted Array 题目分析 本题比较简单。对给定数组的每一个数字的平方。并对结果进行排序。 思路 遍历每一个元素,相乘自身。塞入新数组。 再用sort函数排序。 最终代码 <?phpclassSolution{functionsortedSquares($A){$z=[];foreach($Aas$b){$z[]=$b*$b;}sort($z);return$z;}} ...