mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update 169
This commit is contained in:
parent
0c2438e7c4
commit
25b502367c
@ -14,7 +14,16 @@
|
||||
|
||||
## 思路三: 位运算
|
||||
如果将每个数都转换为二进制的话,那么对于每一位上就只能是0或1。对每一位,取出现次数较多的数(0或1),这样组成的数就是主元素。
|
||||
|
||||
时间复杂度O(n)。
|
||||
|
||||
## 思路四: 求中位数
|
||||
|
||||
思路一对nums进行了排序,然后nums[n/2]就是主元素。其实不用完全排序,我们可以用快排partition的思想在O(n)的平均时间复杂度内求得中位数(见[215求第k大的数题解](215.%20Kth%20Largest%20Element%20in%20an%20Array.md))。我们可以使用STL中的`nth_element`,`nth_element`保证第k(从0开始)个元素是位于最终排序位置的,所以我们令 k = size/2 即把中位数放在了最终位置。
|
||||
|
||||
|
||||
|
||||
|
||||
# C++
|
||||
## 思路一
|
||||
``` C++
|
||||
@ -56,10 +65,20 @@ public:
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
for (int i = 0; i < 32; i++)
|
||||
if(bit[i] > nums.size() / 2) major |= (1 << i);
|
||||
return major;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## 思路四
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
int majorityElement(vector<int>& nums) {
|
||||
nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
|
||||
return nums[nums.size() / 2];
|
||||
}
|
||||
};
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user