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:レコードの使用ハッシュマップ数

2地図への後、ハッシュマップとnums.length / 2比較、これよりも大きい、両方の値数を超え示すN /

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 ビュー890 000 +

おすすめ

転載: blog.csdn.net/u012124438/article/details/104089745