👉🏻 Day3
字符串中找出最长的字符串
mycode:
#include <iostream>
#include<vector>
using namespace std;
int main() {
vector<string> v;
string str;
getline(cin,str);
for(int i =0;i<str.size();i++)
{
string s;
while(isdigit(str[i]))
{
s.push_back(str[i++]);
}
v.push_back(s);
}
string longdigit = v[0];
for(int i = 1;i<v.size();i++)
{
if(v[i].size()>longdigit.size())
{
longdigit = v[i];
}
}
cout<<longdigit<<endl;
}
数组中出现超过一半的数字
mycode:
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型vector
* @return int整型
*/
int MoreThanHalfNum_Solution(vector<int>& numbers) {
//求出数组的一半长度
int halfsize = 0;
if (numbers.size() % 2)
halfsize = (numbers.size() - 1) / 2;
else
halfsize = (numbers.size()) / 2;
//对其排序
sort(numbers.begin(), numbers.end());
int maxnum;
for (int i = 0; i < numbers.size(); i++)
{
int count = 1;
while (i != numbers.size()-1 && numbers[i] == numbers[i + 1])
{
count++;
i++;
}
if (count > halfsize)
{
maxnum = numbers[i - 1];
}
}
return maxnum;
}
};