面试题39. 数组中出现次数超过一半的数字

1、解法一:哈希表

时间O(n),空间O(n/2);

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;
        int len = nums.length;
        for (int i = 0; i < nums.length; i ++) {
            if(map.get(nums[i]) == null){
                map.put(nums[i], 1);
            } else{
                int n = map.get(nums[i]);
                map.put(nums[i], n + 1);
            }

            if (map.get(nums[i]) > len/2)
                res = nums[i];
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 2, 2, 2, 4, 5};
        int res = new Solution().majorityElement(arr);
        System.out.println(res);
    }
}

2、解法二:排序后取中位数

时间O(nlogn),空间O(1);

import java.util.Arrays;

class Solution {
    public int majorityElement(int[] nums) {
        int len = nums.length;
        Arrays.sort(nums);
        int res = nums[len/2];
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 2, 2, 2, 4, 5};
        int res = new Solution().majorityElement(arr);
        System.out.println(res);
    }
}

3、解法三:摩尔投票法(很新颖的解法,一般想不到)

注意:相当于一换一,不同的两者一旦遇见就同归于尽,最后活下来的值都是相同的,即要求的结果;

时间O(n),空间O(1);

class Solution {
    public int majorityElement(int[] nums) {
        int res = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (count == 0){
                res = nums[i];
                count ++;
            }
            else {
                if (res == nums[i])
                    count ++;
                else
                    count --;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 2, 2, 2, 4, 5};
        int res = new Solution().majorityElement(arr);
        System.out.println(res);
    }
}

你可能感兴趣的:(LeetCode)