Squares of a Sorted Array Solutions in C++
Number 977
Difficulty Easy
Acceptance 72.2%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/squares-of-a-sorted-array/// Author : Hao Chen// Date : 2019-03-26class Solution {public:vector<int> sortedSquares(vector<int>& A) {// find the place, negative numbers are right, positive number are right.// two pointer, one goes left, another goes right.//using binary search algorithmconst int len = A.size();int low = 0, high = len- 1;int mid =0;while (low <= high) {mid = low + (high - low)/2;if (A[mid] >= 0 ) high = mid - 1;if (A[mid] < 0 ) low = mid + 1;}//TRICKY: make sure A[mid] <= 0 or A[mid] is A[0]if (A[mid] > 0 && mid > 0 ) mid--;//cout << mid << " - "<< A[mid]<< endl;vector<int> result;low = mid; high = mid+1;while ( low >=0 && high < len ) {if ( abs(A[low]) < abs(A[high]) ) {result.push_back(A[low] * A[low]);low --;}else {result.push_back(A[high] * A[high]);high++;}}for (;low >= 0; low--) result.push_back(A[low] * A[low]);for (;high<len; high++) result.push_back(A[high] * A[high] );return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/squares-of-a-sorted-array//// Author : liuyubobobo/// Time : 2019-01-19#include <iostream>#include <vector>using namespace std;/// Sorting/// Time Complexity: O(nlogn)/// Space Complexity: O(1)class Solution {public:vector<int> sortedSquares(vector<int>& A) {for(int& e: A)e = e * e;sort(A.begin(), A.end());return A;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/squares-of-a-sorted-array//// Author : liuyubobobo/// Time : 2019-01-20#include <iostream>#include <vector>using namespace std;/// Two Pointers/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:vector<int> sortedSquares(vector<int>& A) {int n = A.size(), i = 0, j = n -1;vector<int> ret;while(i <= j)if(abs(A[i]) > abs(A[j]))ret.push_back(A[i] * A[i]), i ++;elseret.push_back(A[j] * A[j]), j --;reverse(ret.begin(), ret.end());return ret;}};int main() {return 0;}