【leetcode】【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.

二、问题分析

①排序,取中间值;②举个例子“1,1,1,2,3”,从头开始遍历,tmp指向第一个1,count=1;然后count=2,3;碰到2,count=2;碰到3,count=1;加入count=0,重新设置tmp值,并重新计数,最后输出tmp即可。具体的看代码。

三、Java AC代码

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

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


你可能感兴趣的:(java,LeetCode,array)