码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 977. Squares of a Sorted Array

时间:2019-06-03 10:45:38      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:click   code   isp   意义   show   open   div   代码   one   

977. Squares of a Sorted Array(有序数组的平方)

 

题目:

 

  给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

 

  示例 1:

  输入:[-4,-1,0,3,10]
  输出:[0,1,9,16,100]

  示例 2:

  输入:[-7,-3,2,3,11]
  输出:[4,9,9,49,121]

 

  提示:

    1.   1 <= A.length <= 10000
    2.   -10000 <= A[i] <= 10000
    3.   A 已按非递减顺序排序。

 

思路:

 

  非递减顺序,再加上存在负数,可以通过在两端比较:先取head和tail表示两端的位置,比较两个数的平方,平方较大者,放到新数组的靠后位置。

  (真要偷懒可以直接用sort,但是这样就没啥意义了)

 

代码:

 

技术图片
 1     public int[] sortedSquares(int[] A) 
 2     {
 3         int len = A.length;
 4         int head = 0;
 5         int tail = len-1;
 6         int [] B = new int [len] ;
 7         while(head <= tail)
 8         {
 9             len--;
10             int i = A[head]*A[head];
11             int j = A[tail]*A[tail];
12             if(i>j)
13             {
14                 B[len] = i;
15                 head++;
16             }
17             else
18             {
19                 B[len] = j;
20                 tail--;
21             }
22         }
23         return B;
24     }
View Code

 

LeetCode 977. Squares of a Sorted Array

标签:click   code   isp   意义   show   open   div   代码   one   

原文地址:https://www.cnblogs.com/blogxjc/p/10966177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!