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

题目标签:Array

  题目给了我们一组 从小到大的 integers,让我们平方数字 并且 也排序成 从小到达。

  因为有负数在里面,平方后,负数在array的位置会变动。

  可以设left 和 right pointers,从两边遍历,比较一下两个平方后的数字,把大的那个 放入新建的array的末尾。

  具体看code。

Java Solution:

Runtime beats 100.00% 

完成日期:02/03/2019

关键点:two pointers

 1 class Solution 
 2 {
 3     public int[] sortedSquares(int[] A) 
 4     {
 5         int left = 0;
 6         int right = A.length - 1;
 7         int[] result = new int[A.length];
 8         int inputIndex = right;
 9         
10         while(left <= right)
11         {
12             int leftInt = A[left] * A[left];
13             int rightInt = A[right] * A[right];
14             
15             if(leftInt > rightInt)
16             {
17                 result[inputIndex] = leftInt;
18                 left++;
19                 inputIndex--;
20             }
21             else 
22             {
23                 result[inputIndex] = rightInt;
24                 right--;
25                 inputIndex--;
26             }
27         }
28         return result;
29     }
30 }

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

猜你喜欢

转载自www.cnblogs.com/jimmycheng/p/10468691.html