LeetCode Problem 169: Majority Element查找多数元素

描述: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:Moore voting algorithm--每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。时间复杂度:O(n)

 class Solution {
public:
int majorityElement(vector<int> &num) { int elem = ;
int count = ; for(int i = ; i < num.size(); i++) { if(count == ) {
elem = num[i];
count = ;
}
else {
if(elem == num[i])
count++;
else
count--;
} }
return elem;
}
  };

思路2:随机挑选一个元素,检查是否是多数元素。时间复杂度:Average:O(n)。期望查找次数 <2

 class Solution {
public:
int majorityElement(vector<int> &num) { int count = ; for(;;) {
if(num.size() == )
return num[];
else {
int i = rand() % (num.size() - );
for(int j = ; j < num.size(); j++) {
if(num[j] == num[i])
count++;
}
if(count > (num.size() / ))
return num[i];
else {
count = ;
continue;
}
}
}
}
  };

附LeetCode建议解决方案:

LeetCode Problem 169: Majority Element查找多数元素

上一篇:java基础(3)-多线程(1)


下一篇:01-老马jQuery教程-jQuery入口函数及选择器