【LeetCode-169】找出数组中出现次数大于? n/2 ?次的数

2021-02-11 07:18

阅读:365

标签:lse   hashtable   eth   sort   get   element   new   count   ==   

// method 1
    public static int majorityElement_1(int[] num) {

        int major=num[0], count = 1;
        
        for (int i=1; i) {
            if (count == 0) {
                count++;
                major=num[i];
            } else if (major == num[i]) {
                count++;
            } else count--;
            
        }
        return major;
    }
    
    // method 2
    public static int majorityElement_2(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
    
    // method 3
    public static int majorityElement_3(int[] nums) {
         Map myMap = new HashMap();
            //Hashtable myMap = new Hashtable();
            int ret=0;
            for (int num: nums) {
                if (!myMap.containsKey(num))
                    myMap.put(num, 1);
                else
                    myMap.put(num, myMap.get(num)+1);
                if (myMap.get(num)>nums.length/2) {
                    ret = num;
                    break;
                }
            }
            return ret;
    }

 

【LeetCode-169】找出数组中出现次数大于? n/2 ?次的数

标签:lse   hashtable   eth   sort   get   element   new   count   ==   

原文地址:https://www.cnblogs.com/nachdenken/p/12737711.html


评论


亲,登录后才可以留言!