Abstract thinking in C Programming-algorithm analysis-most elements

Source: Internet
Author: User

[Problem]

Compile the following functions: int majorityelement (INT array [], int N );

This function returns most elements in the array. A majority element is a value that accounts for an absolute majority (at least 51%. If most elements do not exist, the constant nomajorityelement is returned. This function must meet the following conditions:
1. It must be run at O (n) time.
2. The additional space of O (1) must be used. In other words, individual temporary variables can be used instead of any temporary array. It cannot be solved by recursion, because as the number of recursive layers deepens, space is required to store stack frames.

3. The value of any element in the array cannot be changed.

[Code]

#include <stdio.h>void MajorityElement(int array[], int n){int majority, i, count;majority = array[0];count = 1;for(i = 1; i < n; i++){if(majority != array[i]){if(count == 0){majority = array[i];count++;}else{count--;}}else{count++;}}if(count > 0)printf("MajorityElement: %d\n", majority);elseprintf("NoMajorityElement\n");}main(){int array[5] = {1, 2, 1, 2, 3};MajorityElement(array, 5);}


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.