数组——有序数组的平方

文章目录

题目顺序:代码随想录算法公开课,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 <= numsi <= 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;
    }
};
相关推荐
小胖xiaopangss9 分钟前
BRpc使用
c++·rpc
绿算技术37 分钟前
Mooncake 与绿算ForinnBase GroundPool如何联手打破推理僵局?
科技·算法·架构
-森屿安年-41 分钟前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream43 分钟前
Cartographer详细讲解
c++·人工智能·自动驾驶
森G44 分钟前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
碧海蓝天20221 小时前
C++法则24:在标准 C++ 中,没有任何可移植的方式判断指针 T* pt 指向的内存位置是否已经 构造了对象,程序员必须手动跟踪哪些元素已构造。
java·开发语言·c++
老余捞鱼1 小时前
线性回归实战:5步验证你的量化因子是否真有效
算法·金融·回归·线性回归·ai量化
charlie1145141911 小时前
现代C++指南:Lambda,让我们用另一种方式持有函数
开发语言·c++
想吃火锅10051 小时前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
森G1 小时前
77、线程池原理和实现------服务器源码解析----云视频服务项目
服务器·c++·qt