[LeetCode169] Majority element to find the number of occurrences in an array greater than N/2

Source: Internet
Author: User

Topic:

Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .

Assume that the array was non-empty and the majority element always exist in the array.

Idea: You can use dictionary to record the number of occurrences of each number in the array and the number of output occurrences greater than N/2

Or, after sorting the array, the number in the middle of the array is the

Code:

 Public classSolution { Public intMajorityelement (int[] nums) {        intTime = Nums. Length/2; /*using Dictionary dictionary<int,int> dic = new dictionary<int,int> (); for (int i = 0;i < Nums. length;i++) {if (!dic. ContainsKey (Nums[i]) dic.        ADD (nums[i],0); } for (int j = 0;j < Nums. length;j++) {if (DIC).                ContainsKey (Nums[j])) {dic[nums[j]]++;            if (Dic[nums[j]] > Time) return nums[j];        }} return 0; */                //sort the array, the middle number is theArray.Sort (nums); returnNums[time]; }}

    

[LeetCode169] Majority element to find the number of occurrences in an array greater than N/2

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.