[leetcode]Majority Element
来源:互联网 发布:ubuntu好看的主题 编辑:程序博客网 时间:2024/05/14 00:05
原题
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路
This problem is required to get the majority element appeard. As it appears more than [n/2] times. So we can compare two elements, if they do not have the same value, we can delete them. And at last, the only left element must be the one we want to get. The time complexity is O(n)
代码
int majorityElement(int* nums, int numsSize) { int element = 0; int count = 0; for(int i = 0; i < numsSize; i++) { if(count == 0) { element = nums[i]; count++; }else { if(element == nums[i]) { count++; }else { count--; } } } return element;}
运行结果
42 / 42 test cases passed.
Status:Accepted
Runtime: 8 ms
Submitted: 10 minutes ago
1 0
- 【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
- C/C++--char *s 和 char s[] 的区别
- Maven更新代码四步走【笔记】
- 日经社説 20150814 「戦争の半世紀」じっくり学ぶ歴史教育に
- xcode工程文件格式(Xcode Project File Format)详解
- 原根与离散对数
- [leetcode]Majority Element
- epoll_create, epoll_ctl和epoll_wait
- 博客第一天
- 社説 20150814 終戦70年 平和の堅持へ国際協調貫こう
- JS语言核心
- TCP中用到的定时器
- 并查集
- fcntl使用说明
- EntityFramework中常用的数据删除方式