leetcode 两题

66 plus one

用digit这个数组代表数值,要将此数加一,carry=1时代表需要进位,要在数组最左边插入一个1

class Solution:  
    def plusOne(self, digits):  
        len_s = len(digits)  
        carry = 1  
        for i in range(len_s - 1, -1, -1):  
            total = digits[i] + carry  
            digit = int(total % 10)  
            carry = int(total / 10)  
            digits[i] = digit  
        if 1 == carry:  
            digits.insert(0, 1)  
        return digits 

167.two sum || input array is sorted

要找到满足两个数,他们的和等于target,返回他们在数组中的下标,可以选择类似夹逼的思想,左右两边都进行逼近,如果两数之和小于target,就将左边的数向右移一个,大于target则将右边的数向左移一个

class Solution(object):
    def twoSum(self, numbers, target):
        left, right = 0, len(numbers) - 1
        while left < right:
            if numbers[left] + numbers[right] == target:
                return [left + 1, right + 1]
            elif numbers[left] + numbers[right] > target:
                right -= 1
            else:
                left += 1

猜你喜欢

转载自blog.csdn.net/qq_40169140/article/details/80155583