记录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