首页 > 学院 > 开发设计 > 正文

leecode 解题总结:168. Excel Sheet Column Title

2019-11-08 01:24:02
字体:
来源:转载
供稿:网友
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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.分析:寻找出现次数至少为n/2的数字。这是编程之美的题目。出现次数大于一半。可以采用如果设置当前数出现次数超过一半,那么每次碰到另一个数,这个计数器就减少,当减少到0的时候,就重新设置另一个数举例:2 2 3 3 4 4 3 3 3初始设定2为超过一半的数字,2的计数器变为2后,连续遇到,两个3变成0,输入:92 2 3 3 4 4 3 3 392 2 4 4 3 3 3 3 3输出:33*/class Solution {public:    int majorityElement(vector<int>& nums) {        if(nums.empty())		{			return 0;		}		int size = nums.size();		int value = nums.at(0);		int count = 1;		for(int i = 1 ; i < size ; i++)		{			if(nums.at(i) == value)			{				count++;			}			else			{				count--;			}			if(0 == count)			{				value = nums.at(i);				count = 1;			}		}		return value;    }};void PRocess(){	 vector<int> nums;	 int value;	 int num;	 Solution solution;	 vector<int> result;	 while(cin >> num )	 {		 nums.clear();		 for(int i = 0 ; i < num ; i++)		 {			 cin >> value;			 nums.push_back(value);		 }		 int temp = solution.majorityElement(nums);		 cout << temp << endl;	 }}int main(int argc , char* argv[]){	process();	getchar();	return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表