记录leetcode十一天(66.Plus One+vector的emplace优化)

本文详细解析了LeetCode上的经典题目PlusOne,探讨了如何将一个表示为vector的整数加1,并讨论了两种主要情况:进位但位数不变和进位导致位数增加。同时,文章分享了使用emplace优化代码后的显著效果,包括速度提升和内存减少。

记录leetcode十一天(66.Plus One+vector的emplace)

1.题目

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

看起来就有点复杂,大概就是说有一个vector整型的一位数组,把整个当成一个整数,加1,再转换为原来的表达方式。

2.例子

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

3.解析

很简单,主要考虑两种情况。
1.加1后进位,但是整数位数不变。

input: [1,3,9]
Output: [1,4,0]

2.加1后进位,整数位数也增加。

input: [9,9,9,9]
Output: [1,0,0,0,0]

4.代码

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        
        vector<int> numPlusOne;
        int j=digits.size()-1;
        digits[j]=digits[j]+1;//加1
        for(;j>0 && digits[j]==10;j--)//第一种境况,进位但位数不变。
        {
           
            digits[j]=0;
            digits[j-1]=digits[j-1]+1;       
        }  
        if(digits[j]==10 && j==0)//第二种情况,位数改变
        {
           digits[j]=1;//最前面变1
           digits.push_back(0);//最后补0      
        }
        
        return digits;
    }

5.emplace优化

优化完速度忽然变快,内存变小。emplace 最大的作用是避免产生不必要的临时变量,而push_back就会产生。emplace就像insert,emplace_back就像push_back。
.cbegin()返回一个const_iterator,指向容器的第一个元素。
代码只改一句:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        
        vector<int> numPlusOne;
        int j=digits.size()-1;
        digits[j]=digits[j]+1;
        for(;j>0 && digits[j]==10;j--)
        {
           
            digits[j]=0;
            digits[j-1]=digits[j-1]+1;      
         
        }  
        if(digits[j]==10 && j==0)
        {
            digits[j]=0;
            digits.emplace(digits.cbegin(), 1); //改在啦这里!!      
        }
        
        return digits;
    }
};

关于emplace_back和push_back区别很好的例子:
https://blog.youkuaiyun.com/p942005405/article/details/84764104

关于begin( )和cbegin( )异同:
https://blog.youkuaiyun.com/u010987458/article/details/70949112

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值