【LEETCODE】35、169题, Majority Element

package y2019.Algorithm.array;

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

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.array
 * @ClassName: MajorityElement
 * @Author: xiaof
 * @Description: 169. Majority Element
 * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
 * You may assume that the array is non-empty and the majority element always exist in the array.
 *
 * Input: [3,2,3]
 * Output: 3
 *
 * 获取重复数据达到n/2的数据
 *
 * @Date: 2019/7/2 10:50
 * @Version: 1.0
 */
public class MajorityElement {

    //自己的解法,效率极底。。。
    public int solution(int[] nums) {
        //我们考虑用hash的原理做
        Map<Integer, Integer> map = new HashMap();
        for(int i = 0; i < nums.length; ++i) {
            if(map.containsKey(nums[i])) {
                map.put(nums[i], map.get(nums[i]) + 1);
            } else {
                map.put(nums[i], 1);
            }
        }
        //取出出现次数最大的
        Integer result = null;
        int maxTimes = 0;
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if(entry.getValue() > maxTimes) {
                maxTimes = entry.getValue();
                result = entry.getKey();
            }
        }

        return result;
    }


    //我们换个思路,这题majority element always exist in the array. 必定存在这个元素
    //那么我们只要求出最大出现次数的元素,那么就一定满足要求
    public int solution2(int[] nums) {

        int count = 1;
        int result = nums[0];

        for(int i = 1; i < nums.length; ++i) {
            if(count == 0) {
                //当前元素出现次数以及衰减完毕
                result = nums[i]; //换新元素
                count++;
            } else if (nums[i] == result) {
                //如果重复出现
                count++;
            } else {
                count--;
            }
        }

        return result;
    }

    public static void main(String args[]) {

        int pres[] = {2,2,1,1,1,2,2,1,1};
        System.out.println(new MajorityElement().solution2(pres));

    }

}

 

posted @ 2019-07-02 11:16  cutter_point  阅读(71)  评论(0编辑  收藏  举报