[Leetcode Java] Majority Element, leetcodemajority

Source: Internet
Author: User

[Leetcode Java] Majority Element, leetcodemajority

The questions are as follows:

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

You may assume that the array is non-empty and the majority element always exist in the array.

Solution 1 is as follows: a more common solution is also stupid

public class Solution {    public int majorityElement(int[] num) {        HashMap<Integer,Integer> map=new HashMap<>();        for(int a:num){            if(map.get(a)!=null){                int i=map.get(a);                 map.put(a,i+1);            }            else{                map.put(a,1);            }        }        List<Map.Entry<Integer,Integer>> list =new ArrayList<>();        list.addAll(map.entrySet());        Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){           public int compare(Map.Entry<Integer,Integer> m1,Map.Entry<Integer,Integer> m2){               return m2.getValue()-m1.getValue();           }         });        return list.get(0).getKey();    }}

The second solution is as follows: Make full use of the conditions given in the question

public class Solution {    public int majorityElement(int[] num) {        HashMap<Integer,Integer> map=new HashMap<>();        for(int a:num){            if(map.get(a)!=null){                int i=map.get(a);                 map.put(a,i+1);            }            else{                map.put(a,1);            }        }        for(Map.Entry<Integer,Integer> m:map.entrySet()){            if(m.getValue()>num.length/2){                return m.getKey();            }        }        return 0;    }}
The third solution is my search on the Internet: I feel tired after reading it ..

public class Solution {    public int majorityElement(int[] num) {        Arrays.sort(num);        return num[num.length/2];    }}
WTF ....


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.