88. 最大升序子数组和(简单)
题目要求:
给定一个正整数组成的数组 nums ,返回 nums 中一个升序子数组
的最大可能元素和。
子数组是数组中的一个连续数字序列
。
已知子数组 [numsl, numsl+1, …, numsr-1, numsr] ,若对所有 i(l <= i < r),numsi < numsi+1 都成立,则称这一子数组为 升序 子数组。注意,大小为 1 的子数组也视作 升序 子数组。
题目分析:
依次从每个元素开始向后遍历,分别计算每次遍历的最大数组和,并取其中的最大值即可。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
class Solution
{
public:
int maxAscendingSum(vector<int>& nums)
{
int res = 0;
int l = 0;
while (l < nums.size()) // 从nums中的每个元素开始计算升序子数组和,一共计算n次子数组和
{
int cursum = nums[l];
l++;
while (l < nums.size() && nums[l] > nums[l - 1]) // 当下一个元素大于前一个元素时,是升序数组,求和
{
cursum += nums[l];
l++;
}
res = max(res, cursum); // 更新res和cursum中的最大值,作为当前最大升序子数组和
}
return res;
}
};
int main()
{
vector<int> nums = { 10,20,30,5,10,50 };
Solution s;
cout << "数组中的元素为:";
for (int num : nums)
{
cout << num << ", ";
}
cout << endl;
int res = s.maxAscendingSum(nums);
cout << "最大升序子数组和为:" << res << endl;
system("pause");
return 0;
}
89. 截断句子(简单)
题目要求:
句子 是一个单词列表,列表中的单词之间用单个空格
隔开,且不存在前导或尾随空格。每个单词仅由大小写英文字母组成(不含标点符号)。
例如,“Hello World”、“HELLO” 和 “hello world hello world” 都是句子。
给你一个句子 s 和一个整数 k ,请你将 s 截断 ,使截断后的句子仅含前 k
个单词。返回 截断 s 后得到的句子。
题目分析:
根据题意,统计句子中空格的数量以及最后一个单词来计算句子中的单词总数,再根据k的大小取出相应的子串。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
class Solution
{
public:
string truncateSentence(string s, int k)
{
int n = s.size();
int end = 0, count = 0;
for (int i = 0; i <= n; i++)
{
if (i == n || s[i] == ' ') // 如果遍历到空格或者最后一个元素,元素个数加1
{
count++;
if (count == k) // 如果当前统计的元素个数=k,取出当前元素下标作为句子的断点
{
end = i;
break;
}
}
}
return s.substr(0, end);
}
};
int main()
{
string str = "Hello how are you Contestant";
int k = 4;
cout << "原句为:";
for (auto &e : str)
{
cout << e << " ";
}
cout << endl;
Solution s;
string res = s.truncateSentence(str, k);
cout << "截断后为:";
for (auto &e : res)
{
cout << e << " ";
}
cout << endl;
system("pause");
return 0;
}
90. 数组元素积的符号(简单)
题目要求:
已知函数 signFunc(x) 将会根据 x 的正负返回特定值:
如果 x 是正数,返回 1 。
如果 x 是负数,返回 -1 。
如果 x 是等于 0 ,返回 0 。
给定一个整数数组nums
。令 product 为数组 nums 中所有元素值的乘积。
返回 signFunc(product) 。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
class Solution
{
public:
int arraySign(vector<int>& nums)
{
int sign = 1; // 初始化输出符号
for (auto num : nums)
{
if (num == 0) // 如果有一个元素是0,乘积也为0
{
return 0;
}
if (num < 0) // 每出现一次负数,结果的符号改变一次
{
sign = -sign;
}
}
return sign;
}
};
int main()
{
vector<int> nums = { -1,-2,-3,-4,3,2,1 };
Solution s;
cout << "原数组为:";
for (auto num : nums)
{
cout << num << ", ";
}
cout << endl;
int res = s.arraySign(nums);
cout << "数组元素积的符号为:" << res << endl;
system("pause");
return 0;
}