169. Majority Element 难度:Easy 类别:分治
2016-09-11 11:06
393 查看
题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
思路:
此题要求选出一个数组中出现次数最多的那一个数,可用分治算法的思想,将整个数组分成两个部分,先分别筛选出这两部分中出现次数最多的数,记为x和y,如果x等于y,则返回x,如果x不等于y,则x和y都是最终结果的候选,此时需要遍历整个链表考察x和y出现的次数,出现次数较多的就是最终返回的结果。复杂度T(n) = 2T(n/2) + O(n),所以T(n) = O(nlogn)。
程序:
int majorityElement(int* nums, int numsSize) {
if(numsSize == 0||numsSize == 1)
return *nums;
int x = majorityElement(nums,numsSize / 2);
int y = majorityElement(nums + numsSize / 2,numsSize - numsSize / 2);
if(x == y)
return x;
else
{
int countX = 0;
int countY = 0;
for(int i = 0;i < numsSize;i++)
{
if(*(nums + i) == x)
countX++;
else if(*(nums + i) == y)
countY++;
}
return countX > countY ? x : y;
}
}
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.
思路:
此题要求选出一个数组中出现次数最多的那一个数,可用分治算法的思想,将整个数组分成两个部分,先分别筛选出这两部分中出现次数最多的数,记为x和y,如果x等于y,则返回x,如果x不等于y,则x和y都是最终结果的候选,此时需要遍历整个链表考察x和y出现的次数,出现次数较多的就是最终返回的结果。复杂度T(n) = 2T(n/2) + O(n),所以T(n) = O(nlogn)。
程序:
int majorityElement(int* nums, int numsSize) {
if(numsSize == 0||numsSize == 1)
return *nums;
int x = majorityElement(nums,numsSize / 2);
int y = majorityElement(nums + numsSize / 2,numsSize - numsSize / 2);
if(x == y)
return x;
else
{
int countX = 0;
int countY = 0;
for(int i = 0;i < numsSize;i++)
{
if(*(nums + i) == x)
countX++;
else if(*(nums + i) == y)
countY++;
}
return countX > countY ? x : y;
}
}
相关文章推荐
- 【LeetCode】169. Majority Element(Easy)解题报告
- Leetcode 169. Majority Element[easy]
- [leetcode 169. Majority Element]easy |week4
- 【LeetCode】169.Majority Element (Easy)
- 215. Kth Largest Element in an Array 难度:medium 类别:分治
- LeetCode 169. Majority Element (Easy)
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- 169. Majority Element [easy] (Python)
- LeetCode 169. Majority Element (Easy)
- 169. Majority Element Easy
- Leetcode解题笔记 169.Majority Element [Easy]
- 169. Majority Element----Array----Easy----20160925
- 【Divide and Conquer】169. Majority Element(easy)
- [Leetcode 169, Easy] Majority Element
- Leetcode 169. Majority Element (Easy) (cpp)
- Leetcode 169 Majority Element 分治
- LeetCode Problem 169: Majority Element查找多数元素
- 169. Majority Element (数组)
- 15算法课程 169. Majority Element
- leetcode 每日一题 169. Majority Element