LeetCode/solutions/169. Majority Element.md
2019-09-13 23:08:41 +08:00

62 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [169. Majority Element](https://leetcode.com/problems/majority-element/description/)
# 思路
题目要求就是求数组主元素,主元素就是在数组中出现次数超过元素个数一半的元素,题目保证主元素一定存在。
## 思路一: 排序
若对数组nums进行排序则nums[n/2]就是主元素。
时间复杂度为O(nlogn)。
## 思路二: 投票算法
因为主元素总是存在。所以每出现两个不一样的数就可以忽视这两个数。最终剩下的就是主元素。
我们可以从前往后遍历如果某数和当前major相同那么count++否则count--如果count为零了那么当前major应该改成当前这个数。
时间复杂度O(n)。
## 思路三: 位运算
如果将每个数都转换为二进制的话那么对于每一位上就只能是0或1。对每一位取出现次数较多的数(0或1),这样组成的数就是主元素。
时间复杂度O(n)。
# C++
## 思路一
``` C++
// 提交结果为16ms
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
```
## 思路二
``` C++
// 提交结果为12ms较思路一有提升
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major = nums[0], count = 0;
for(int num : nums){ // 范围for语句
if(major == num) count++;
else if(count == 1) major = num;
else count--;
}
return major;
}
};
```
## 思路三
``` C++
// 提交结果20ms
class Solution {
public:
int majorityElement(vector<int>& nums) {
vector<int>bit(32);
for (int num: nums){
for (int i = 0; i < 32; i++)
if(num & (1 << i)) bit[i]++;
}
int major=0;
for (int i = 0; i < 32; i++) {
if(bit[i] = bit[i] > nums.size() / 2) major += bit[i] * (int)pow(2, i);
}
return major;
}
};
```