Majority Element

1. Title

Majority Element

2. Http address

https://leetcode.com/problems/majority-element/

3. The question

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.

4 My code(AC)

 1         // Accepted
 2        public static int majorityElementTwo(int[] nums) {
 3         
 4            Arrays.sort(nums);
 5            int len = nums.length;
 6            int count,bf;
 7            bf = nums[0];
 8            count=1;
 9            for(int i = 1 ; i < len; i++)
10            {
11                if( count > len /2)
12                {
13                    return bf;
14                }
15                
16                if( nums[i] == bf)
17                {
18                    count++;
19                }else{
20                    bf = nums[i];
21                    count = 1;
22                }
23                
24            }
25            return nums[len-1];
26        }
27        

 

posted @ 2015-11-16 20:57  ordi  阅读(140)  评论(0编辑  收藏  举报