[关闭]
@zimenglan 2015-01-30T10:47:59.000000Z 字数 1889 阅读 1361

Majority Element

leetcode bit-opearaion map sort majority


原题链接


题意

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.

解法

code

  1. class Solution {
  2. public:
  3. // 41 ms
  4. int majorityElement(vector<int> &num) {
  5. const int bitCount = 32;
  6. const int zero = 0;
  7. vector<int> bitRes(bitCount, zero);
  8. for(int i = 0; i < num.size(); i++) {
  9. for(int j = 0; j < bitCount; j++) {
  10. if(num[i] & (1 << j)) {
  11. bitRes[j]++;
  12. }
  13. }
  14. }
  15. int candidate = 0;
  16. const int baseLen = num.size() / 2;
  17. for(int i = 0; i < bitCount; i++) {
  18. // 如果个数>=len(num)/2+1, 则该位为1, 否则为0
  19. if(bitRes[i] > baseLen) {
  20. candidate += (1 << i);
  21. }
  22. }
  23. return candidate;
  24. }
  25. // O(N·logN): time
  26. // 46 ms
  27. int majorityElement2(vector<int> &num) {
  28. sort(num.begin(), num.end());
  29. return num[num.size() / 2];
  30. }
  31. // O(n): time, O(1): space
  32. // 27 ms
  33. // see: http://stackoverflow.com/questions/3740371/finding-the-max-repeated-element-in-an-array
  34. int majorityElement3(vector<int> &num) {
  35. int k = 0;
  36. int res;
  37. for(int i = 0; i < num.size(); i++) {
  38. if(k == 0) {
  39. res = num[i];
  40. k = 1;
  41. } else {
  42. if(res == num[i]) {
  43. k++;
  44. } else {
  45. k--;
  46. }
  47. }
  48. }
  49. return res;
  50. }
  51. // O(N'·logN' + O(N')): time, where N' is the number of unique elements of array num
  52. // 48 ms
  53. // O(N'): space
  54. int majorityElement4(vector<int> &num) {
  55. map<int, int> res;
  56. for(int i = 0; i < num.size(); i++) {
  57. res[num[i]]++;
  58. }
  59. int maxIdx = 0;
  60. int candidate;
  61. for(map<int, int>::iterator it = res.begin(); it != res.end(); it++) {
  62. if(maxIdx < it->second) {
  63. maxIdx = it->second;
  64. candidate = it->first;
  65. }
  66. /* or
  67. if(it->second > num.size() / 2) return it->first;
  68. */
  69. }
  70. return candidate;
  71. }
  72. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注