169. Ask for the number of public

Source: Internet
Author: User

Given an array of size n , find the majority of them. A majority is an element that appears in an array more than ? n/2 ? a number of times.

You can assume that the array is non-empty, and that the given array always exists in the majority.

Example 1:

Input: [3,2,3] Output: 3

Example 2:

Input: [2,2,1,1,1,2,2] Output: 2

Number of occurrences greater than? n/2 ?

Solution One:
classSolution { Public:    intMajorityelement (vector<int>&nums) {        intres=0, counts=0;  for(intx:nums) {            if(counts==0) {res=x; Counts=1; }Else if(res==x) + +counts; Else--counts; }        returnRes; }};---------------------L_aster Source: CSDN Original: https://blog.csdn.net/gl486546/article/details/79783937?utm_source=copyCopyright NOTICE: This article is for bloggers original article, reprint please attach blog link!

Solution Two:

class Solution {public:    int majorityelement (vector<int>& nums) {        sort (nums.begin (), Nums.end ());         return nums[nums.size ()/2];    }; --------------------- Jiangjiang Jiang Source: CSDN Original: https://  Copyright notice: This article for Bo Master original article, reproduced please attach blog link!

169. Ask for the number of public

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.