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

Majority Number II

时间:2015-07-22 22:46:05      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目描述

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.

Example

Given [1, 2, 1, 2, 1, 3, 3], return 1.

Note
There is only one majority number in the array.
Challenge
O(n) time and O(1) extra space.
.

链接地址

http://www.lintcode.com/en/problem/majority-number-ii/

解法

 int majorityNumber(vector<int> nums){
        // write your code here
         int num1 = 0, num2 = 0;
         int ret1 = 0, ret2 = 0;
         for (int i = 0; i < nums.size(); i++) {
             if (num1 != 0 && ret1 == nums[i]) {
                 num1++;
             } else if (num2 != 0 && ret2 == nums[i]) {
                 num2++;
             } else if (num1 != 0 && num2 != 0) {
                 num1--; 
                 num2--;
             } else if (num1 == 0) {
                 num1 = 1;
                 ret1 = nums[i];
             } else {
                 num2 = 1;
                 ret2 = nums[i];
             }
         }
         int count1 = 0, count2 = 0;
         for (int i = 0; i < nums.size(); i++) {
             if (ret1 == nums[i]) {
                 count1++;
             } else if (ret2 == nums[i]) {
                 count2++;
             }
         }
         if (count1 > count2) {
             return ret1;
         } else {
             return ret2;
         }
    }

算法解释

正如算法Majority Number,同时删除两个元素,现在同时删除三个元素。

版权声明:本文为博主原创文章,未经博主允许不得转载。

Majority Number II

标签:leetcode

原文地址:http://blog.csdn.net/richard_rufeng/article/details/46977055

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