This is a pen question, and it was indeed out. (However, there is still an error in details. The number that appears multiple times may be counted repeatedly, but the last deleted element is not recorded)
Such as the question, ordered array, you can know that the data on both sides after the square is large, and the data in the middle is small.
Therefore, two subscripts can be used to scan from both sides. Delete the number with a large absolute value, count it, and record the absolute value of the deleted Value to avoid repeated counting of the same data multiple times.
Complete code:
1 # include <iostream> 2 # include <vector> 3 # include <algorithm> 4 using namespace STD; 5 6 int squareuniquenum (vector <int> & Ver) {7 int Len = ver. size (); 8 If (LEN <2) 9 return Len; 10 11 int I = 0; 12 Int J = len-1; 13 int pre = ABS (ver [0]); // the absolute value of the last Deleted Data Record 14 int num = 1; // The number is 115 while (I <= J) {16 // delete a number with a large absolute value each time, and record that the deletion is the absolute value of the number. If the absolute value is the same, only 17 if (ABS (ver [I])> ABS (ver [J]) {18 if (pre! = ABS (ver [I]) {// if you have not deleted 19 num ++; 20 pre = ABS (ver [I]); 21} 22 I ++; 23} 24 else {25 if (pre! = ABS (ver [J]) {// If 26 num ++; 27 pre = ABS (ver [J]); 28} 29 J --; 30} 31} 32 return num; 33} 34 35 int main () 36 {37 vector <int> ver ({-5,-3,-1, 1, 2 }); 38 int num = squareuniquenum (VER); // after the number square in the ordered array is obtained, 39 cout <num <Endl; 40 return 0; 41}
What is the number of different numbers after each square of an ordered array? O (N)