###不给自己任何借口
今日题目:
1、数位相加;
2、最大子序列乘积
今日摘录:
据说那些你一笑就跟着你笑的人,不是傻逼就是爱你的人
——安东尼《给不二的情书》
258. Add Digits | Difficulty: Easy
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
tag:数学
题意:将一个非负整数,将所有数位相加直到只有一位
思路:模拟一遍很简单,不过题目希望能用O(1)的方法得到答案而非遍历。
1、
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};
结果:12ms
152. Maximum Product Subarray | Difficulty: Medium
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
tag:数组|DP
题意:求一个数组中的最大连续子序列乘积
思路:
1、类似于连续最大子序列和的方法,但是需要保留一个最大一个最小,因为有正有负,如果碰到负数需要更改之前保留的最大与最小。
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n=nums.size();
if(n==0) return 0;
int res = nums[0];
for(int i=1,imax = res,imin = res;i<n;i++)
{
if(nums[i]<0) swap(imax,imin);
imax = max(nums[i],nums[i]*imax);
imin = min(nums[i],nums[i]*imin);
res = max(res,imax);
}
return res;
}
};
结果:8ms