Determine whether T [0: N] has a primary element in linear time.

Source: Internet
Author: User
Let T [0: n-1] Be an array of n elements. For any element x, set S (x) = {I | T [I] = x }. When | S (x) |> n/2, X is the primary element of T. Design an algorithm to determine whether T [0: n-1] has a primary element. The algorithm is described as follows: A1 A2 A3 A4... AJ + 1... ... An first writes A1 to m, and the counter K is set to 1. Then let m compare A1, A2 ..., If it is the same as M, K adds 1. If it is different, K minus 1. In this case, K = 0 may be compared When AJ is compared. Then, AJ + 1 is retrieved and saved to m, and K is set to 1. Repeat the preceding operation to check all the elements in a [1: N. After this process is completed, K has two possible values: ① K = 0, ② K> 0. When K = 0, a [0: n-1] must have no primary element. When K> 0, a [0: n-1] may have a primary element or no primary element. If a [0: n-1] has a primary element, the m value must be the primary element. Obviously, compare all the elements of m with a [0: n-1], that is, whether M is the primary element of a [0: n-1], that is, a [0: n-1: n-1] whether the primary element exists. The algorithm is as follows:
Template <class T> void mainmember (t a [], int N) {int I, J, K, M; M = A [0]; k = 1; j = 0; for (I = 1; I <n; I ++) {If (M = A [I]) K ++; else k --; if (k = 0) {I ++; if (I> N) break; // the elements in a [0: n-1] have been compared, jump out of M = [I];
K = 1 ;}} if (k = 0) cout <"array A has no primary element! "<Endl; else {for (I = 0; I <n; I ++) if (M = A [I]) J ++ ;} if (j> n/2) cout <"array A contains the primary element. The primary element is:" <m <Endl; else cout <"array A does not contain the primary element! "<Endl ;}

 

Determine whether T [0: N] has a primary element in linear time.

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.