zoukankan      html  css  js  c++  java
  • 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

    // test02.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    using namespace std;
    
    class Solution {
    public:
    	int MoreThanHalfNum_Solution(vector<int> numbers) {
    		int count = 0;
    		int flag = 0;
    		for (int i = 0;i < numbers.size();i++)
    		{ 
    			for (int j = 0;j < numbers.size();j++)
    			{
    				if(numbers[i]==numbers[j])
    				count ++ ;
    			}
    			if (count > (numbers.size() / 2))
    			{ 
    				flag = numbers[i];
    				break;
    			}
    			count = 0;
    		}
    		return flag;
    	}
    };
    
    int main()
    {
       //  vector<int> vec = { 1,2,3,2,2,2,5,4,2 };
    	 vector<int> vec = { 1, 2, 3, 2, 2, 2, 5, 4, 2 };
    	int num = 0;
    	Solution so;
    	num=so.MoreThanHalfNum_Solution(vec);
    	//for (auto it = vec.begin();it != vec.end();it++)
    	//{
    	//	cout<<*it<< "  ";
    	//}
    	//
    	cout << "num:" << num << endl;
    
    	cout << endl;
    
    return 0;
    }
  • 相关阅读:
    predis操作
    mysql 笔记(转载)
    mysql 汉字根据首字母排序
    sql 优化
    update多条不同数据
    解决network is unreachable问题
    开启服务器端口
    数据库开启远程访问
    激活2021.2.1idea
    python向excel追加数据
  • 原文地址:https://www.cnblogs.com/wdan2016/p/5970332.html
Copyright © 2011-2022 走看看