229. Majority Element II
来源:互联网 发布:java代码实现充值功能 编辑:程序博客网 时间:2024/06/06 17:07
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.
方法一:Language-Java Time-O(n) Space-O(1) RunTime-3ms
public class Solution { public List<Integer> majorityElement(int[] nums) { if(nums == null || nums.length == 0) { return new ArrayList<Integer>(); } List<Integer> res = new ArrayList<Integer>(); int len = nums.length; int number1 = nums[0]; int number2 = nums[0]; int count1 = 0; int count2 = 0; for(int i = 0; i < len; i ++) { //以下分支中每次只执行一个 if(nums[i] == number1) { count1 ++; }else if(nums[i] == number2) { count2 ++; }else if(count1 == 0) { number1 = nums[i]; count1 = 1; }else if(count2 == 0) { number2 = nums[i]; count2 = 1; }else { count1 --; count2 --; } } count1 = 0; count2 = 0; for(int i = 0; i < len; i ++) { if(nums[i] == number1) { count1 ++; }else if(nums[i] == number2) //如果只有一个数就不会执行这里 { count2 ++; } } if(count1 > len/3 ) { res.add(number1); } if(count2 > len/3 ) { res.add(number2); } return res; }}
0 0
- 229.Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- 229. Majority Element II
- Android SQLite Example
- NVMe驱动解析-响应I/O请求
- SIFT算法详解
- HashTable源码分析
- Codevs1269 匈牙利游戏
- 229. Majority Element II
- 数据库三范式
- java通过jdbc驱动连接hive操作实例
- 使用QSBR进行安全的内存回收
- Codeforces 724B Batch Sort(暴力枚举)
- 从ActionBar切换到toolBar
- 从零开始写一个简单好用的游戏服务器引擎[2] - 跨平台相关
- mybatis+postgresql insert, update or delete returning *问题
- 电脑的启动过程