|
| 1 | +// Source : https://leetcode.com/problems/squares-of-a-sorted-array/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2019-03-26 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given an array of integers A sorted in non-decreasing order, return an array of the squares of each |
| 8 | + * number, also in sorted non-decreasing order. |
| 9 | + * |
| 10 | + * Example 1: |
| 11 | + * |
| 12 | + * Input: [-4,-1,0,3,10] |
| 13 | + * Output: [0,1,9,16,100] |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * Input: [-7,-3,2,3,11] |
| 18 | + * Output: [4,9,9,49,121] |
| 19 | + * |
| 20 | + * Note: |
| 21 | + * |
| 22 | + * 1 <= A.length <= 10000 |
| 23 | + * -10000 <= A[i] <= 10000 |
| 24 | + * A is sorted in non-decreasing order. |
| 25 | + * |
| 26 | + ******************************************************************************************************/ |
| 27 | + |
| 28 | +class Solution { |
| 29 | +public: |
| 30 | + vector<int> sortedSquares(vector<int>& A) { |
| 31 | + // find the place, negative numbers are right, positive number are right. |
| 32 | + // two pointer, one goes left, another goes right. |
| 33 | + |
| 34 | + //using binary search algorithm |
| 35 | + const int len = A.size(); |
| 36 | + int low = 0, high = len- 1; |
| 37 | + int mid =0; |
| 38 | + while (low <= high) { |
| 39 | + mid = low + (high - low)/2; |
| 40 | + if (A[mid] >= 0 ) high = mid - 1; |
| 41 | + if (A[mid] < 0 ) low = mid + 1; |
| 42 | + } |
| 43 | + |
| 44 | + //TRICKY: make sure A[mid] <= 0 or A[mid] is A[0] |
| 45 | + if (A[mid] > 0 && mid > 0 ) mid--; |
| 46 | + //cout << mid << " - "<< A[mid]<< endl; |
| 47 | + |
| 48 | + vector<int> result; |
| 49 | + low = mid; high = mid+1; |
| 50 | + while ( low >=0 && high < len ) { |
| 51 | + if ( abs(A[low]) < abs(A[high]) ) { |
| 52 | + result.push_back(A[low] * A[low]); |
| 53 | + low --; |
| 54 | + }else { |
| 55 | + result.push_back(A[high] * A[high]); |
| 56 | + high++; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + for (;low >= 0; low--) result.push_back(A[low] * A[low]); |
| 61 | + for (;high<len; high++) result.push_back(A[high] * A[high] ); |
| 62 | + |
| 63 | + return result; |
| 64 | + } |
| 65 | +}; |
0 commit comments