数组——有序数组的平方

文章目录

题目顺序:代码随想录算法公开课,b站上有相应视频讲解

一、题目

977. Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an 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]

Explanation: After squaring, the array becomes [16,1,0,9,100].

After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]

Output: [4,9,9,49,121]

Constraints:

1 <= nums.length <= 104

-104 <= nums[i] <= 104

nums is sorted in non-decreasing order.

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

题目来源: leetcode

二、题解

排序写法

cpp 复制代码
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0;i < n;i++){
            nums[i] = nums[i] * nums[i];
        }
        sort(nums.begin(),nums.end());
        return nums;
    }
};

双指针写法

cpp 复制代码
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        vector<int> res(n,0);
        int index = n - 1;
        for(int i = 0,j = n - 1;i <= j;){
            if(nums[i] * nums[i] > nums[j] * nums[j]){
                res[index--] = nums[i] *nums[i];
                i++;
            }
            else{
                res[index--] = nums[j] * nums[j];
                j--;
            }
        }
        return res;
    }
};
相关推荐
进击的圆儿3 分钟前
分治算法_快速排序专题总结-----分治
算法·排序算法·分治·快排·大根堆·小根堆
前进之路920 分钟前
Leetcode每日一练--35
算法·leetcode
董建光d29 分钟前
【深度学习】目标检测全解析:定义、数据集、评估指标与主流算法
深度学习·算法·目标检测
郝学胜-神的一滴41 分钟前
Linux系统函数link、unlink与dentry的关系及使用注意事项
linux·运维·服务器·开发语言·前端·c++
赵杰伦cpp43 分钟前
list的迭代器
开发语言·数据结构·c++·算法·链表·list
~~李木子~~1 小时前
机器学习集成算法实践:装袋法与提升法对比分析
人工智能·算法·机器学习
老歌老听老掉牙1 小时前
使用 OpenCASCADE 提取布尔运算后平面图形的外轮廓
c++·平面·opencascade
微笑尅乐1 小时前
三种思路彻底掌握 BST 判断(递归与迭代全解析)——力扣98.验证二叉搜索树
算法·leetcode·职场和发展
闻缺陷则喜何志丹1 小时前
【动态规划】数位DP的原理、模板(封装类)
c++·算法·动态规划·原理·模板·数位dp
豆沙沙包?2 小时前
2025年--Lc194-516. 最长回文子序列(动态规划在字符串的应用,需要二刷)--Java版
java·算法·动态规划