leetcode题解日练--2016.8.29

###不给自己任何借口

今日题目:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值