LeetCode -- Majority Element II

Source: Internet
Author: User

LeetCode -- Majority Element II

Given an integer array of size n, find all elements that appear more than limit n/3 times. The algorithm shocould run in linear time and in O (1) space.

This is to calculate an element that appears more than n/3 times in an array.

I haven't figured out how to use the space complexity of O (1) for the moment. The idea is to use hash.

Implementation Code:

public class Solution {    public IList
   MajorityElement(int[] nums)     {        if(nums == null || nums.Length == 0){            return new List
   ();        }        var hash = new Dictionary
    ();        var len = nums.Length;                for (var i = 0;i < len; i++)        {            if(!hash.ContainsKey(nums[i]))            {                hash.Add(nums[i],1);            }            else{                hash[nums[i]]++;            }        }                var ret = new List
     ();        foreach(var k in hash.Keys)        {            if(hash[k] > len / 3){                ret.Add(k);            }        }        return ret;    }}


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.