leetcode -- Majority Element
来源:互联网 发布:邪恶漫画知子伯母全集 编辑:程序博客网 时间:2024/06/05 17:12
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.
在数组不为空的前提下返回出数组中出现超过n/2次的数组元素,简单直接的做法是直接通过两层for循环计算元素的次数,当次数达到n/2时返回当前的元素,算法时间复杂度为O(n^2),空间复杂度为O(1);另一种做法是通过投票算法(投票算法适用于选出数组中出现的次数大于等于数组长度一半的元素)算法时间复杂度为O(n),空间复杂度为O(1)
int majorityElement(int* nums, int numsSize) {
int num = 0, count = 0;
for(int i = 0; i < numsSize; i++) {
if(count == 0)
{
num = nums[i];
count += 1;
}
else if(num == nums[i])
count += 1;
else
count -= 1;
}
return num;
}
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- 设置文件的属性-chmod/chown/truncate/utime/umask
- in 和exists
- 修复MongoDB数据库,解决因Unclean Shutdown导致服务不能启动的问题
- Android类-BroadcastReceiver
- 北航上机测试准备 程序3
- leetcode -- Majority Element
- struts框架本质解析
- Azure RemoteApp(云桌面)的价值和优势
- Android providing resource
- 安装并配置samba
- jsp的内置对象
- 关于NaN isNaN Number、parseInt/parseFloat的整理汇总
- SQL中常用的函数
- maven的多环境配置