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.
自己写了个时间复杂度O(nlogn)的,看见评论区有O(n)的,贴一下贴一下,空间复杂度都是O(1)还看到有用位运算和哈希表的,不过感觉加大了空间的消耗,在此就不贴那两种了
思路就是:因为一定超过n/2以上,所以排个序返回中位数一定是这个数。评论区思路是:假设一个数是答案,然后遇到相同的就cnt++,不同的就cnt--,当cnt为0时就将其换掉,直到最后留下的那个数就是答案。其实就是,每次去掉数组中两个不同的数,那么最后一定会留下出现最多的那个数。
class Solution { //O(nlogn)
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
class Solution { //O(n)
public:
int majorityElement(vector<int>& nums) {
int ans = nums[0];
int cnt = 1;
for (int i = 1; i < nums.size(); ++i) {
if (cnt == 0) {
ans = nums[i];
cnt = 1;
}
else if (nums[i] == ans) cnt++;
else cnt--;
}
return ans;
}
};
229. Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
大于n/3,那最多只会有两个数呗,托腮ing
写法是参照上一题评论区的思想,这题也不能算是自己做的吧
时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> ans;
int ans1 = 0, ans2 = 1;
int cnt1 = 0, cnt2 = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == ans1) cnt1++;
else if (nums[i] == ans2) cnt2++;
else if (cnt1 == 0) {
ans1 = nums[i];
cnt1++;
}
else if (cnt2 == 0) {
ans2 = nums[i];
cnt2++;
}
else cnt1--, cnt2--;
}
cnt1 = 0, cnt2 = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == ans1) cnt1++;
else if (nums[i] == ans2) cnt2++;
}
if (cnt1 > nums.size() / 3) ans.push_back(ans1);
if (cnt2 > nums.size() / 3) ans.push_back(ans2);
return ans;
}
};