What is the number of different numbers after each square of an ordered array? O (N)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.