首页 > 其他 > 详细

leetcode-Majority Element

时间:2015-07-19 17:51:43      阅读:199      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!