码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-Majority Element

时间:2015-07-19 17:54:49      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

Q:

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.

A1:

   1: public class Solution {
   2:     public int majorityElement(int[] num) {
   3:  
   4:         int major=num[0], count = 1;
   5:         for(int i=1; i<num.length;i++){
   6:             if(count==0){
   7:                 count++;
   8:                 major=num[i];
   9:             }else if(major==num[i]){
  10:                 count++;
  11:             }else count--;
  12:  
  13:         }
  14:         return major;
  15:     }
  16: }

A2:

   1: public class Solution {
   2:     public int majorityElement(int[] num) {
   3:         Arrays.sort(num);
   4:         return num[num.length / 2];
   5:     }
   6: }

leetcode-Majority Element

标签:

原文地址:http://www.cnblogs.com/hust-ghtao/p/4658844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!