169.Majority Element
来源:互联网 发布:gtp手机吉他谱软件 编辑:程序博客网 时间:2024/05/29 19:41
/*
题目要求:
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的平方,在提交的时候,时间受限。
后来发现这个题目的多种解法,时间复杂度都小的多
1.两个for循环解决
2.首先进行快速排序或者堆排序,然后直接输出第n/2的元素,必定是主元素
3.主元素算法,先设定一个比较值count=0,然后向后一个数比较,如果相同,则count++;若不同,count--。若相邻两个数都不一样,则count=-1,
这时候将这两个元素删除掉,那么对于剩下的数来说,主元素还是主元素,并不会发生改变。
这是算法的核心思想,这样的话算法的时间复杂度最大才是O(n)
*/
int majorityElement(int* nums, int numsSize)
{
int i,count = 0;
int mainer = nums[0];
for(i=1;i<numsSize;i++)
{
if(mainer!=nums[i])
count--;
else
count++;
if(count==-1)
{
mainer = nums[i+1];
i++;
count = 0;
}
}
if(count>0)
return mainer;
return;
}
题目要求:
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的平方,在提交的时候,时间受限。
后来发现这个题目的多种解法,时间复杂度都小的多
1.两个for循环解决
2.首先进行快速排序或者堆排序,然后直接输出第n/2的元素,必定是主元素
3.主元素算法,先设定一个比较值count=0,然后向后一个数比较,如果相同,则count++;若不同,count--。若相邻两个数都不一样,则count=-1,
这时候将这两个元素删除掉,那么对于剩下的数来说,主元素还是主元素,并不会发生改变。
这是算法的核心思想,这样的话算法的时间复杂度最大才是O(n)
*/
int majorityElement(int* nums, int numsSize)
{
int i,count = 0;
int mainer = nums[0];
for(i=1;i<numsSize;i++)
{
if(mainer!=nums[i])
count--;
else
count++;
if(count==-1)
{
mainer = nums[i+1];
i++;
count = 0;
}
}
if(count>0)
return mainer;
return;
}
阅读全文
0 0
- 169.Majority Element && 229. Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 169.Majority Element
- [leetcode] 169.Majority Element
- 169. Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- 169. Majority Element
- 169. Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- 自定义view四个构造函数代表什么
- C++动态规划算法之数字金字塔【USACO TRAINING】:一道经典的数塔问题
- <模板>计算SG函数-(hdu 1848 Fibonacci again and again)
- HDU 1402 A * B Problem Plus (FFT求高精度乘法)
- mark标记输入流中的当前位置,以便使用reset方法复制到该标记的位置 reset将当前位置复位为上次调用mark方法标记的位置
- 169.Majority Element
- 【Linux】ubuntu首次给root用户设置密码
- [RK3288][Android6.0] 调试笔记 --- ComponentName的使用
- zzuli2174
- android 关于封装tabbar,任意修改样式
- 购物车AngularJs
- 在GitHub多个帐号上添加SSH公钥
- KazaQ's Socks
- Js中JSON.stringify()、JSON.parse()、eval()详解