There is an integer array, and it is known that the number of occurrences is more than half. Please use the O (n) Complexity Algorithm to find this number.

Source: Internet
Author: User

There is an integer array, and we know that the number of occurrences of a number is more than half. Please use the complexity of O (n ).AlgorithmFind this number.

Method 1: Hash linked list

Method 2: Use two variables A and B, where a stores the number in an array and B is used to count. At the beginning, Class B is initialized to 0.

Traverse the array,

If B = 0, make a equal to the current number and B equal to 1;

If the current number is the same as that of a, B = B + 1;

If the current number is different from a, B = B-1.

At the end of the traversal, the number in a is the number to be searched.

The time complexity of this algorithm is O (n), and the space complexity is O (1 ).

C LanguageDescription:

 

 

  1. IntMain ()
  2. {
  3. IntI, A, B;
  4. IntA [10] = {1, 2, 3, 1, 2, 1, 6, 1 };
  5. A = A [5];
  6. B = 0;
  7. For(I = 0; I <10; I ++)
  8. If(B = 0)
  9. {
  10. A = A [I];
  11. B = 1;
  12. }ElseIf(A = A [I])
  13. B ++;
  14. ElseIf(! = A [I])
  15. B --;
  16. Printf ("% d", );
  17. Getchar ();
  18. Return0;
  19. }

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.