977. Squares of a Sorted Array

LeetCode easy оригинал: C# #array #csharp #easy #leetcode #sort

Дан целочисленный массив 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# решение

сопоставлено/оригинал
using 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++ решение

auto-draft, проверить перед отправкой
#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 решение

сопоставлено/оригинал
import 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 решение

сопоставлено/оригинал
class Solution {
    sortedSquares(nums) {
        const ans = nums.map(num => num * num)
        ans.sort((a, b) => a - b)
        return ans
    }
}

Python решение

сопоставлено/оригинал
class Solution:
    def sortedSquares(self, nums: list[int]) -> list[int]:
        ans = [num * num for num in nums]
        ans.sort()
        return ans

Algorithm

Создайте массив квадратов каждого элемента.

Отсортируйте массив квадратов.

Верните отсортированный массив квадратов.

😎

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.