977. Squares of a Sorted Array
leetcode easy
#array#csharp#easy#leetcode#sort
Task
Дан целочисленный массив nums, отсортированный в неубывающем порядке. Верните массив квадратов каждого числа, отсортированный в неубывающем порядке.
Пример:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
C# solution
matched/originalusing System;
using System.Linq;
public class Solution {
public int[] SortedSquares(int[] nums) {
int[] ans = nums.Select(num => num * num).ToArray();
Array.Sort(ans);
return ans;
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public vector<int>& SortedSquares(vector<int>& nums) {
vector<int>& ans = nums.Select(num => num * num).ToArray();
sort(ans.begin(), ans.end());
return ans;
}
}Java solution
matched/originalimport java.util.Arrays;
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = nums[i] * nums[i];
}
Arrays.sort(ans);
return ans;
}
}JavaScript solution
matched/originalclass Solution {
sortedSquares(nums) {
const ans = nums.map(num => num * num)
ans.sort((a, b) => a - b)
return ans
}
}Python solution
matched/originalclass Solution:
def sortedSquares(self, nums: list[int]) -> list[int]:
ans = [num * num for num in nums]
ans.sort()
return ansExplanation
Algorithm
Создайте массив квадратов каждого элемента.
Отсортируйте массив квадратов.
Верните отсортированный массив квадратов.
😎