leetcode刷题(48)——169. 多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

解法1:因为这个数的数量大于n/2,所以排序之后的中位数一定是这个数

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

解法2:分治

class Solution {
    private int countInRange(int[] nums, int num, int lo, int hi) {
        int count = 0;
        for (int i = lo; i <= hi; i++) {
            if (nums[i] == num) {
                count++;
            }
        }
        return count;
    }

   private int majorityElemeec(int[] nums, int lo, int hi) {
        // base case; the only element in an array of size 1 is the majority
        // element.
        if (lo == hi) {
            return nums[lo];
        }

        // recurse on left and right halves of this slice.
        int mid = (hi-lo)/2 + lo;
        int left = majorityElemeec(nums, lo, mid);
        int right = majorityElemeec(nums, mid+1, hi);

        // if the two halves agree on the majority element, return it.
        if (left == right) {
            return left;
        }

        // otherwise, count each element and return the "winner".
        int leftCount = countInRange(nums, left, lo, hi);
        int rightCount = countInRange(nums, right, lo, hi);

        return leftCount > rightCount ? left : right;
    }

    public int majorityElement(int[] nums) {
        return majorityElemeec(nums, 0, nums.length-1);
    }
}

解法3:使用hashmap记录次数

放入map之后,对hashmap的value都和nums.length /2比较,大于这个的,说明数目超过n/2

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class Solution {
   /**
	 * 求超过一半的数(利用哈希表)
	 * 加一操作:a+1=-~a
	 * @param nums
	 * @return
	 */
    public static int majorityElement(int[] nums) {
		int half = nums.length >> 1;

		Map<Integer/* 数字 */, Integer/* 次数 */> map = new HashMap<Integer, Integer>();
		for (int i : nums) {
			if (map.containsKey(i)) {
				map.put(i, map.get(i)+1);
			} else {
				map.put(i, 1);
			}
		}

		for (Entry<Integer, Integer> entry : map.entrySet()) {
			if (half < entry.getValue()) {
				return entry.getKey();
			}
		}
		return 0;
	}
}
发布了204 篇原创文章 · 获赞 684 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/u012124438/article/details/104089745