数组——有序数组的平方

文章目录

题目顺序:代码随想录算法公开课,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;
    }
};
相关推荐
程序猿乐锅5 小时前
【数据结构与算法 | 第二篇】 双链表的增删改查
数据结构
xyy1236 小时前
C# Polly 弹性策略库指南
算法
郝学胜-神的一滴6 小时前
中级OpenGL教程 020:巧用数组与循环实现多点点光源渲染,告别冗余代码重构方案
c++·unity·游戏引擎·godot·图形渲染·unreal
zmzb01036 小时前
C++课后习题训练记录Day160
开发语言·c++
沫璃染墨6 小时前
现代C++⊂C++11篇(一)列表初始化全解 & std::initializer_list
开发语言·c++
阿米亚波6 小时前
【C++ STL】std::forward_list
开发语言·c++·笔记·stl·visual studio·forward_list
geovindu7 小时前
go: Recursion Algorithm
开发语言·后端·算法·golang·递归算法
十五年专注C++开发7 小时前
qobject_cast转换失败原因分析
c++·qt·dynamic_cast·qobject_cast
小保CPP7 小时前
OCR C++ Tesseract按单词识别字符
c++·人工智能·ocr·模式识别·光学字符识别
库克克7 小时前
【C++】多态
开发语言·c++