LeetCode day5

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)

注意方法优化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值