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

169. Majority Element && 229. Majority Element II

时间:2016-07-25 07:01:48      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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. 

Hide Similar Problems
 (M) Majority Element II
 
 
public class Solution {
  public int majorityElement(int[] num) {
    int major = num[0];
    int count = 1;
    //The majority number has enough counts to cover all other numbers
    for (int i = 1; i < num.length; ++i) {
      if (count == 0) {
        ++count;
        major = num[i];
      } else if (major == num[i]) {
        ++count;
      } else
        --count;
    }
    return major;
  }
}

 

 

229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?
  2. Do you have a better hint? Suggest it!

Hide Tags

Hide Similar Problems
 (E) Majority Element
public class Solution {
  public List<Integer> majorityElement(int[] nums) {
    List<Integer> results = new ArrayList<>();
    if (nums == null || nums.length == 0)
      return results;

    int n1 = nums[0];
    int n2 = nums[0];
    int count1 = 0;  //count keeps a "relative" count of current number
    int count2 = 0;
    int len = nums.length;

    for (int i = 0; i < len; ++i) {
      if (nums[i] == n1)
        ++count1;
      else if (nums[i] == n2)
        ++count2;
      else if (count1 == 0) {
        n1 = nums[i];
        count1 = 1;
      } else if (count2 == 0) {
        n2 = nums[i];
        count2 = 1;
      } else {
        //Zeros were check beforehand to make sure counts won‘t go negative
        --count1; 
        --count2;
      }
    }

    count1 = 0;
    count2 = 0;
    for (int i = 0; i < len; i++) {
      if (nums[i] == n1)
        ++count1;
      else if (nums[i] == n2)
        ++count2;
    }
    if (count1 > len / 3)
      results.add(n1);
    if (count2 > len / 3)
      results.add(n2);
    return results;
  }
}

 

 
 

169. Majority Element && 229. Majority Element II

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5702180.html

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