38. Count and Say
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
Solution in C++:
关键点:理解题意 && 会类型之间的转换
思考过程:理解了比较久的题意才懂,每个term是按着count-and-say的规律在读上一个term,就开始码代码,主要问题就存在循环控制对象的选择、处理对象的选择以及类型转换之间的问题处理。
string countAndSay(int n) {
vector<string> vec{"1","11","21","1211","111221"};
if ( n <= 5 )
return vec[n-1];
string temp = vec[4];
for ( int i = 4; i < n - 1; ++i ){
// count and say
string s = "";
int size = temp.size();
int nums = 1;
int j;
for (j = 1; j < size; ++j){
if(temp[j] == temp[j-1]){
++nums;
} else{
stringstream stream;
char c = nums + '0';
stream << c;
s += stream.str();
stream.clear();
stream << temp[j-1];
s += temp[j-1];
nums = 1;
}
}
stringstream stream;
char c = nums + '0';
stream << c;
s += stream.str();
stream.clear();
stream << temp[j-1];
s += temp[j-1];
vec.push_back(s);
temp = s;
}
return vec[n-1];
}
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solution in C++:
关键点:几种情况的考虑&&舍弃和的条件
思考过程:由于本人对分治的写法还没熟悉,时间又比较紧,所以这次就采用暴力的方法写了这题的解。思考很简单,当数组全是小于0的时候,需要从中挑选一个最大的负数,但其中有非零的时候,那么负数是否加入sum之中就考察加完之后是否还大于0,显然小于0之后,再加后面的只会更小。
int maxSubArray(vector<int>& nums) {
size_t size = nums.size();
int sum = 0;
int max = nums[0];
for(size_t i = 0; i < size; ++i){
if(nums[i] > 0 || sum + nums[i] > 0)
sum += nums[i];
else
sum = 0;
if (max < 0){
if (max < nums[i])
max = nums[i];
} else{
if (max < sum)
max = sum;
}
}
return max;
}
小结
今天可能收获的不是很明显,因为很多遗漏的知识并没有及时去补充,也慢慢发现前面遗漏的知识放到后面去补充只会越积越多的事实,所以从明天开始不仅得抓紧点时间还得赶紧补一下之前的知识了。日复日,月复月,年复年,每天进步一点,相信自己一定能成功。