Input - (“mon 10:00 am”, mon 11:00 am) Output - [11005, 11010, 11015…11100] Output starts with 1 if the day is monday, 2 if tuesday and so on till 7 for sunday Append 5 min interval times to that till the end time So here it is 10:05 as first case, so its written as 11005 2nd is 10:10 so its written as 11010
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = “1 + 1” Output: 2
Example 2:
Input: s = “ 2-1 + 2 “ Output: 3
Example 3:
Input: s = “(1+(4+5+2)-3)+(6+8)” Output: 23
Constraints:
`1 <= s.length <= 3 105*sconsists of digits,‘+’,‘-‘,‘(‘,‘)’, and‘ ‘.
*srepresents a valid expression.
*‘+’is **not** used as a unary operation (i.e.,“+1”and“+(2 + 3)”is invalid).
*‘-‘could be used as a unary operation (i.e.,“-1”and“-(2 + 3)”` is valid). There will be no two consecutive operators in the input.
Every number and running calculation will fit in a signed 32-bit integer.
# 1-(2+3)+(4+5) # 1+2+3 defcalculate(self, s: str) -> int: res, num, stack, sign = 0, 0, [], 1 s += '+' for char in s: if char == ' ': continue if char.isdigit(): num = num * 10 + int(char) if char == '+': res += sign * num sign = 1 num = 0 if char == '-': res += sign * num sign = -1 num = 0 if char == '(': stack.append(res) # [-4+] stack.append(sign) # sign = 1 res = 0 if char == ')': res += sign * num # 9 prev_sign = stack.pop() # + tmp = stack.pop() # -4 res = tmp + prev_sign * res # -4 +9 # sign = 1 next one will be +-, so num = 0 and sign doesn't matter num = 0 # else: # res += char return res
defproductExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) res, product = [1] * n, nums[0] for i inrange(1, n): res[i] = product # [1, 1] product *= nums[i] product = nums[-1] # 2 for i inrange(n - 2, -1, -1): res[i] *= product # [2, 1] product *= nums[i] return res
算法分析:
时间复杂度为O(n),空间复杂度O(1)
若可以用除法算法II解题思路:
按照定义用数学方法,但只要注意一个0和两个0的情况
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
defproductExceptSelf(self, nums: List[int]) -> List[int]: product, zero_count = 1, 0 for n in nums: if n != 0: product *= n else: zero_count += 1 if zero_count > 1: return [0] * len(nums) res = [] for i inrange(len(nums)): if nums[i] == 0: res.append(product) elif zero_count > 0: res.append(0) else: res.append(int(product / nums[i])) return res