算法Coding练习--leetcode (Python 数学运算)

1.1 LeetCode[1] Two Sum:

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解答:首先题目限制条件给的比较充足,如每个array都有一个唯一解,相同的元素不能使用两次。因此可以考虑使用字典的方式来解决该问题。

class Solution(object):
    def twoSum(self, nums, target):
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i

举例说明: nums = [1, 3,3,4,5,7], target = 6

i = 0时,nums[0] = 1 not in buff_dict,因此此时buff_dict[6-1=5] = 0,记为buff_dict = {5:0}

i = i+1 = 1, nums[1] =  3 not in buff_dict, 因此此时buff_dict[6-3=3]=1, 此时buff_dict = {5:0, 3:1}

i = i+1 = 2, nums[2]=3 in buff_dict,因此此时返回[buff_dict[num[2]=3]=1, i=2]


1.2 LeetCode[66] Plus One:

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.

解答:设置一个从后往前处理的序列,如果当前序列的array值小于9,则对应位置的值加1,返回处理后的结果;若当前位置的值等于9,则该位置的值置为0,序列向前移动一位继续处理。若序列移动到第一个元素且第一个元素的值为9,则整个array的前面插入1,再返回处理后的array

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        A = [1]
        i = len(digits)-1
        while i>=0:
            if digits[i]<9:
                digits[i] = digits[i]+1
                return digits
            else:
                digits[i] = 0
                i = i - 1
                if i == -1:
                    A.extend(digits)
                    return A

 

1.3 LeetCode[167]  Two Sum II - Input array is sorted(答案与LeetCode[1]相似,也可采用二分查找的方式进行搜索)

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

1.4 LeetCode[258]   Add Digits 

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:
Input: 38
Output: 2 
Explanation: 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?

解答:如例中数字38=30+8 ==> 3+8=(30%9)+8=11 ==> 1+1=(10%9)+1 ==> 38%9=2

class Solution:
    def addDigits(self, num: int) -> int:
        if num == 0:
            res = 0
        else:
            res = num%9 if num%9>0 else 9
        return res

1.5 LeetCode[371]   Sum of Two Integers 

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1: Input: a = 1, b = 2, Output: 3
Example 2: Input: a = -2, b = 3, Output: 1

该题目的考察点是位运算,计算过程如下:

补码=原码取反+1,即当a^b或者(a&b)<<1为负值时,取其补码进行后续操作
class Solution:
    def getSum(self, a: int, b: int) -> int:
        MAX = 0x7FFFFFFF
        mask = 0xFFFFFFFF
        while b!=0:
            a,b = (a^b)&mask, ((a&b)<<1)&mask
        return(a if a <= MAX else ~(a ^ mask))

但是该题目存在漏洞,只是说明了不能使用+和-号,但是没有说不能用函数,因此简单粗暴的代码如下:

class Solution(object):
    def getSum(self, a, b):
        return sum([a,b])

 

你可能感兴趣的:(代码与思路)