Leetcode 169. Majority Element to find the most occurrences of the number---------Java

Source: Internet
Author: User

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.

Given an array, the element in which the weight is the largest, (the element appears more than half the number of times).

Intuitive ideas, HashMap, very slow

 Public classSolution { Public intMajorityelement (int[] nums) {Map Map=NewHashmap<integer, integer>(); intLen =nums.length; if(len = = 1){            returnNums[0]; }         for(intnum:nums) {            if(Map.containskey (num)) {intCount = (int) map.get (num); if((count + 1) > LEN/2){                    returnnum; } Else{map.put (num, Count+ 1); }            } Else{map.put (num,1); }        }        return-1; }}

Discuss above see this question very perfect summary:

1. Sorting sort

 Public int majorityElement1 (int[] nums) {    arrays.sort (nums);     return NUMS[NUMS.LENGTH/2];}

2, HashMap

3. Moore's voting algorithm (best algorithm)

Very ingenious, time O (n), Space O (1), is to record the current element and the current element of the "winning" number (more than other elements).

 Public int majorityElement3 (int[] nums) {    int count=0, ret = 0;      for (int  num:nums) {        if (count==0)            = num;         if (num!=ret)            count--;         Else             Count++    ;    } return ret;}

4, bit arithmeticBit manipulation 

By recording the numbers on each one, it is better to compare the third algorithm to the result.

 Public intMajorityelement (int[] nums) {    int[] bit =New int[32];  for(intnum:nums) for(inti=0; i<32; i++)             if((Num>> (31-i) & 1) = = 1) Bit[i]++; intRet=0;  for(inti=0; i<32; i++) {Bit[i]=bit[i]>nums.length/2?1:0; RET+ = bit[i]* (1<< (31-i)); }    returnret;}

Leetcode 169. Majority Element to find the most occurrences of the number---------Java

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.