Home > Back-end >  Leetcode - 977.
Leetcode - 977.

Time:09-22

Topic: https://leetcode-cn.com/problems/squares-of-a-sorted-array/

Method one: square add sorting
For each element of an array of square first, and then sorted,
Method 2: double needle method: because this is an ordered array, two Pointers point to the right and the left, then square value comparison of the two, and then put the larger in the right, in turn,
The class Solution {
Public:
Vector SortedSquares (vector & A) {
Int len=A.s considering ();
Vector Ans (len);
Int a=0, b=len - 1, I=len - 1;
While (I & gt;=0)
{
Int lef=A * A [A]; [A] * int rig=A [b] A [b];
If (lef & gt; Rig)
{
Ans [I]=lef.
a++;
}
The else ans [I]=rig, b -;
i--;
}
Return ans.

}
};

Method 2: binary finding boundary, and then extend
The class Solution {
Public:
Vector SortedSquares (vector & A) {
Int len=A.s considering ();
Vector Ans.
Int l=1, r=len - 1, mid=0;
While (l & lt; R)
{
Mid=(int) (l + r + 1) & gt;> 1;
Int len=A.s considering ();
If (A/mid & lt; L==0) mid;
The else r=mid - 1;
}
R=l + 1;
for (int i=0; i If (l & lt; 0 {
Ans. The push_back (A * A [r] [r]);
R++;
}
Else if (r & gt; Len)={
Ans. The push_back (A [l] * [l] A);
L -;
}
The else {
If ((A [l] * [l] A) & lt;=(A * A [r] [r]]) {
Int temp=A * A [l] [l];
Ans. The push_back (temp);
L -;

}
The else {
Ans. The push_back ((A * A [r] [r]));
R++;
}
}
}
for (int i=0; i {
Cout & lt; }
Return ans.
}
};

At first, the problems encountered during definition vector Ans when defined as vector Ans (len), the output is 0; This is due to the inside of the vector function push_back in vector class action to join a at the end of the vector data,
In fact is equal to make the following error:
Const int size=7.
Int ia [size]={0, 1, 1, 2, 3, 5, 8};
VectorFor (int x=0; Ix & lt; The size; + + ix)
Ivec. Push_back (ia [ix]);
Ivec contain 14 elements at the end of the program, ia elements from the eighth element inserted,




  • Related