数组——有序数组的平方

文章目录

题目顺序:代码随想录算法公开课,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;
    }
};
相关推荐
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧1 小时前
C语言_数据结构总结8:链式队列
c语言·开发语言·数据结构·链表·visualstudio·visual studio
讨厌下雨的天空1 小时前
C++之list
开发语言·c++·list
Icomi_2 小时前
【神经网络】0.深度学习基础:解锁深度学习,重塑未来的智能新引擎
c语言·c++·人工智能·python·深度学习·神经网络
真就死难3 小时前
完全日期(日期枚举问题)--- 数学性质题型
算法·日期枚举
不知道取啥耶3 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
花间流风3 小时前
晏殊几何学讲义
算法·矩阵·几何学·情感分析
@心都3 小时前
机器学习数学基础:42.AMOS 结构方程模型(SEM)分析的系统流程
人工智能·算法·机器学习
Murphy_lx4 小时前
数据结构(树)
数据结构
tt5555555555554 小时前
每日一题——三道链表简单题:回文,环形合并有序
数据结构·链表
我想吃烤肉肉4 小时前
leetcode-sql数据库面试题冲刺(高频SQL五十题)
数据库·sql·leetcode