首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode】977. Squares of a Sorted Array数组 双指针

【LeetCode】977. Squares of a Sorted Array数组 双指针

作者头像
韩旭051
发布2020-06-23 11:15:37
2180
发布2020-06-23 11:15:37
举报
文章被收录于专栏:刷题笔记刷题笔记

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2:

Input: [-7,-3,2,3,11] Output: [4,9,9,49,121]

Note:

1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order.

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array

跟刚才那道题很像,找到一个神奇思路,两边的平方一定是最大的,so~双指针从两边往中间移动就很简单了,一开始从中间往两边走就麻烦很多

但是这个时间速度很慢~百分之23%

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int n=A.size();
        vector<int> num(n);
        if(n==0){
            return num;
        }
        int a=0;
        int b=n-1;
        int na,nb;
        while(n>0&&a!=b){
            n--;
            na=A[a]*A[a];
            nb=A[b]*A[b];
            if(na>nb){
                a++;
                num[n]=na;
            }else{
                b--;
                num[n]=nb;
            }
        }
        if(n>0) num[0]=A[a]*A[a];
        return num;
    }
};

暴力的老哥都比我快

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        //暴力求解 双指针
        int start =0,end=A.size()-1;
        vector<int> res;
        while(start<=end){
            if(abs(A[start])>abs(A[end])){
                res.push_back(A[start]*A[start]);
                start++;
            }else{
                res.push_back(A[end]*A[end]);
                end--;
            }
        }
        reverse(res.begin(),res.end());
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 跟刚才那道题很像,找到一个神奇思路,两边的平方一定是最大的,so~双指针从两边往中间移动就很简单了,一开始从中间往两边走就麻烦很多
  • 但是这个时间速度很慢~百分之23%
  • 暴力的老哥都比我快
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档