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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
分析
从第一个数组元素开始,一直到array.size()/2个元素,依次判断是不是该数组的主要元素,具体有一下规则:
1.设置一个计数量,每次发现一个与当前元素相同的元素,计数量加一,注意计数量从1开始,一个循环后要重置,最后计数量大于array.size()/2则输出目标元素;
2.外层循环从序号0到array.size()/2-1进行,若该数组存在重要元素,则这个范围内一定存在重要该数组的重要元素;
3.内层循环从目标元素的下一个元素开始,依次遍历完数组,符合要求的计数加一。
4.最后输出目标元素,若无重要元素,输出-1.
#代码
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
int same,flag=1;
for (int i = 0; i < nums.size()/2; i++) {
same = nums[i];
for (int j = i + 1; j < nums.size(); j++) {
if (same == nums[j])
flag++;
}
if (flag > nums.size() / 2)
return same;
flag = 1;
}
return -1;
}
};
int main() {
Solution s;
int i;
char c = 'Y';
vector<int> nums = { 1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2 };
/*
while (cin >> i) {
nums.push_back(i);
cout << "y or n ?" << endl;
cin >> c;
if (c != 'y' || c != 'Y') {
break;
}
}
*/
int num = s.majorityElement(nums);
printf("num: %d\n",num);
return 0;
}
/**
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
**/
时间复杂度和空间复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(n2) | O(1) |
注意方法优化