---
title: "find the majority element"
author: "Vitas_Wang"
date: "2015-12-26T17:18:45Z"
tags: []
categories: ["编程语言"]
slug: "find-the-majority-element"
draft: false
lastmod: "2015-12-26T17:18:45Z"
id: 2266780
url: "https://jaler.iteye.com/blog/2266780"
---

this is a question from leetcode:

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.

If you want to get the best solution, then you must analyst and make use of all the information provided in the problem.

question analysis:
the key hint is that the majority element always exist. So that means that the count of majority element is great than the count of all other element, so the 
count(majority) - count(others) > 0.

below is the best solution:

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

```