66. Plus One

114 阅读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.

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

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

解题思路: 暴力破解法

这个题目的解题思路有很多,首先我们可以将数组变成一个真正的数字, 然后再将+1 以后的数字变成数组. 但是这样的解法太耗时. 我们可以使用遍历数组的方式来解题. 我们首先给数组的最后一个元素 +1, 然后开始倒序遍历数组, 如果当前元素 >9, 也就是产生了进位, 我们就将当前元素变为0, 将前一位 +1, 最后判断第一个元素是不是需要进位做同样的处理
时间复杂度: O(n)

示例代码

func plusOne(_ digits: [Int]) -> [Int] {
    var tempArray = digits
    tempArray[tempArray.count - 1] += 1
    for i in 0..<tempArray.count-1 {
        if tempArray[tempArray.count - 1 - i] > 9 {
            tempArray[tempArray.count - 1 - i] = 0
            tempArray[tempArray.count - 2 - i] += 1
        }
    }
    if tempArray[0] > 9 {
        tempArray[0] = 0
        tempArray.insert(1, at: 0)
    }
    return tempArray
}

上边的方式,我们还需要额外判断第一个元素, 所以,可以进行一下改进, 直接使用while 做循环, 判断每一个元素是不是有需要进位, 当index 是0时,就做最后的插入1,跳出循环

示例代码

func plusOne(_ digits: [Int]) -> [Int] {
    var tempArray = digits
    var index = tempArray.count - 1
    tempArray[index] += 1

    while tempArray[index] == 10 {
        tempArray[index] = 0
        if index == 0 {
            tempArray.insert(1, at: 0)
            break
        }else {
            tempArray[index - 1] += 1
        }
        index -= 1
    }
    return tempArray
}