Article directory
One, multiple choice
eg1
eg2
eg3
eg4
eg5
2. Programming questions
eg1
[Solution ideas]:
Traverse the string, use cur to record the continuous number string, if it encounters non-digit characters, it means that a continuous number string is over, then compare the number string with the previous number string, if it is longer , then update the longer number string to ret.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
string cur;
string ret;
//<= s.size();防止出现abcd12345ed125ss123456789
for(int i = 0; i <=s.size(); ++i)
{
//如果是数字字符就插入cur
if('0' <= s[i] && s[i] <= '9')
{
cur += s[i];
}
else
{
//判断cur的长度是否大于ret的长度
if(cur.size() > ret.size())
{
ret = cur;
}
//清空cur
cur.clear();
}
}
cout << ret << endl;
return 0;
}
eg2
[Problem-solving idea 1]:
Idea 1: After the array is sorted, if the number that meets the conditions exists, it must be the number in the middle of the array. Although this method is easy to understand, its time complexity of O(NlogN) is not optimal due to the quick sorting involved.
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers)
{
sort(numbers.begin(), numbers.end());
int index = numbers.size() / 2;
return numbers[index];
}
};
[Problem-solving idea 2]: Mode:
the number that appears more than half the length of the array. If the two numbers are not equal, eliminate the two numbers. In the worst case, eliminate one mode and one non-mode at a time. , then if there is a mode, the number left at the end must be the mode
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers)
{
int result = numbers[0];
int times = 1;
for(int i = 1; i < numbers.size(); ++i)
{
if(times != 0)
{
if(result == numbers[i])
{
++times;
}
else
{
--times;
}
}
else
{
result = numbers[i];
times = 1;
}
}
return result;
}
};