• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
THE WAY I AM
博客园    首页    新随笔    联系   管理    订阅  订阅
977. Squares of a Sorted Array有序数组的平方

网址:https://leetcode.com/problems/squares-of-a-sorted-array/

双指针法

把左端的元素和右端的元素比较后挑出绝对值大的,将其平方放入ans中,并且将指针往中间移动

不断循环上述过程,直至两指针重合。注意处理重合位置

最后将 ans 通过 reverse 反转一下就可以了

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int i = 0, j = A.size()-1;
        vector<int> ans;
        while(i != j)
        {
            if(abs(A[i]) < abs(A[j]))
            {
                ans.push_back(A[j]*A[j]);
                j--;
            }
            else
            {
                ans.push_back(A[i]*A[i]);
                i++;
            }
        }
        ans.push_back(A[i]*A[i]);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

 

posted on 2019-04-09 18:37  549  阅读(94)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3