字符串算法——查找数组多数元素(Majority Element II)
来源:互联网 发布:java ssh协议jar包 编辑:程序博客网 时间:2024/06/17 07:26
问题:
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.
思路一:与前述的majority element类似,采用直接遍历计算元素出现的次数,如果超过总长度的
思路二:同前述的查找Majority element类似,舍弃掉三个不同的值是不影响原数组中的Majority element;在这里最多存在两个Majority element
class Solution { public List<Integer> majorityElement(int[] nums) { // if(nums.length<1)return null; int max1=Integer.MAX_VALUE;//存储出现次数最多的元素 int max2 =Integer.MIN_VALUE;//存储出现次数第二多的元素 int count1 = 0; int count2 = 0; for(int i=0;i<nums.length;i++){//遍历数组 if(nums[i]==max1){ count1++; }else if(nums[i]==max2){ count2++; }else if(count1 ==0){ max1= nums[i]; count1 = 1; }else if(count2 == 0){ max2 =nums[i]; count2 =1; }else{//舍弃三个不同值 count1--; count2--; } } List<Integer> res = new ArrayList<>(); count2 = count1 =0; //计算元素出现的次数 for(int i = 0;i<nums.length;i++){ if(nums[i]==max1){ count1++; } if(nums[i]==max2){ count2++; } } //判断majority element if(count1>nums.length/3){ res.add(max1); } if(count2>nums.length/3){ res.add(max2); } return res; }}
阅读全文
0 0
- 字符串算法——查找数组多数元素(Majority Element II)
- 字符串算法——查找数组中多数元素(Majority Element)
- 169. Majority Element 查找多数元素
- LeetCode--Majority Element II & 多数投票算法
- LeetCode--Majority Element II & 多数投票算法
- LeetCode 题解 169. Majority Element(查找多数元素)
- 第二周:169. Majority Element(查找多数元素)
- LeetCode-169:Majority Element (数组中的多数元素)
- 【数组】Majority Element II
- 169. Majority Element (寻找多数元素)
- [LeetCode]169. Majority Element(多数元素)
- 字符串算法——查找二维数组中元素(Search a 2D Matrix II)
- leetcode——Majority Element II
- Leetcode——229. Majority Element II
- Algorithms—229.Majority Element II
- 字符串算法——旋转数组中查找目标值(有重复元素)( Search in Rotated Sorted Array II)
- 字符串算法——查找有序数组旋转后最小值(有重复元素)(Find Minimum in Rotated Sorted Array II)
- Majority Element && Majority Element II
- STL容器用法(不完整)
- Rust: map中的问题,两种写法有什么不同?
- HDOJ 1106 排序
- CentOS 6.5下通过yum安装MongoDB记录
- web前端性能优化总结
- 字符串算法——查找数组多数元素(Majority Element II)
- 编译原理---文法和语言
- java中的匿名内部类
- Could not open a connection to SQL Server [2]
- 上拉刷新,下拉加载
- Docker实践教程
- 作业四 顺序表的排序和查找操作(未完成)
- 微信扫码支付 模式一
- 哈希表和完美哈希