lintcode-medium-Majority Number II
2016-03-29 18:04
330 查看
Given an array of integers, the majority number is the number that occurs
Find it.
Notice
There is only one majority number in the array.
Example
Given
Challenge
O(n) time and O(1) extra space.
more than 1/3of the size of the array.
Find it.
Notice
There is only one majority number in the array.
Example
Given
[1, 2, 1, 2, 1, 3, 3], return
1.
Challenge
O(n) time and O(1) extra space.
public class Solution { /** * @param nums: A list of integers * @return: The majority number that occurs more than 1/3 */ public int majorityNumber(ArrayList<Integer> nums) { // write your code if(nums == null || nums.size() == 0) return 0; Integer num1 = null; Integer num2 = null; int count1 = 0; int count2 = 0; for(int i = 0; i < nums.size(); i++){ int temp = nums.get(i); if(num1 == null){ num1 = temp; count1 = 1; } else if(num1 == temp){ count1++; } else if(num2 == null){ num2 = temp; count2 = 1; } else if(num2 == temp){ count2++; } else{ count1--; count2--; if(count1 == 0){ num1 = temp; count1 = 1; } if(count2 == 0){ num2 = temp; count2 = 1; } } } count1 = 0; count2 = 0; for(int i = 0; i < nums.size(); i++){ if(num1 == nums.get(i)) count1++; if(num2 == nums.get(i)) count2++; } if(count1 > nums.size() / 3) return num1; return num2; } }
相关文章推荐
- 文件操作
- MTK 电池曲线配置
- 通过rails打开数据库
- error LNK2001: 无法解析的外部符号 __imp__IsWindowUnicode@4
- 西普实验吧CTF-考考你的程序功底
- sublime3安装常用插件
- Laxcus大数据管理系统2.0 (1) - 摘要和目录
- Permutations
- 杭电2063
- [UE4][Custom Animation Graph Node]Evaluate Pose by Curve
- 通过rails打开数据库
- iOS Build Question
- MongoDB全文索引用法
- 排序算法系列之八大排序算法性能比較-从实验结果分析
- 反射 vo与po的转换
- 复杂事件处理技术概览(二)
- linux--shell--iftop
- android项目框架中libs之**.so
- window下搭建hexo
- 使用Multiplayer Networking做一个简单的多人游戏例子-3/3(Unity3D开发之二十七)