Majority Element 主要的元素
来源:互联网 发布:十块吧淘宝优站 编辑:程序博客网 时间:2024/05/16 07:27
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.
方法1:
直接排序,中间的元素一定是出现次数最多的元素。
public int majorityElement1(int[] nums) { Arrays.sort(nums); return nums[nums.length / 2]; }
运行时间:
方法2:
排序的方式,时间复杂度是O (NlogN)
下面介绍一个时间复杂度为O (N)的算法。
// moore voting algorithm public int majorityElement2(int[] nums) { int pre = nums[0]; int count = 1; for (int num : nums) { if (num == pre) { count++; } else { count--; } if (count == 0) { pre = num; count = 1; } } return pre; }
运行时间:
虽然最后时间差不多。
参考资料:
https://leetcode.com/discuss/24971/o-n-time-o-1-space-fastest-solution
1 0
- Majority Element 主要的元素
- Majority Element / Majority Element 2-主要元素
- LeetCode 169. Majority Element (数组的主要元素、摩尔投票算法)
- LeetCode 169 Majority Element(主要元素)(vector、map)
- LeetCode-169.229. Majority Element II (JAVA)主要元素
- Majority Element众数元素的解法分析
- [LeetCode] Majority Element 最主要的元素
- Majority Element:主元素
- LeetCode 229 Majority Element II(主要元素II)(Array)(Boyer–Moore majority vote algorithm)
- 229. Majority Element II 找出出现超过一定数量的元素
- Majority Element II:求个数多余1/3的元素
- Majority Element:找最多且多于一半的元素
- LeetCode--Majority Element(出现次数最多的元素)Python
- 169. Majority Element (寻找多数元素)
- 169. Majority Element | 数组中的主元素
- [LeetCode]169. Majority Element(多数元素)
- 169. Majority Element 查找多数元素
- Majority Element 找出一个数组中出现次数最多的元素
- HBaseCon 2013: Using Coprocessors to Index Columns in an Elasticsearch Cluster
- Android进程间通信之Socket
- Java容器类的深入理解
- 数据挖掘之七种常用的方法
- JSON入门学习
- Majority Element 主要的元素
- 数据分析与可视化工具小谈
- UVa 213 Message Coding
- c语言解析json
- 技术发展瓶颈的突破
- Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登录(二)
- 补、C++第九次上机实验
- 图像卷积与滤波的一些知识点
- ReactNative-Cocoapods-Swift-Project