#1 TowSum
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ j=len(nums)-1 ind = [] indv = [] r,l = 0,0 minn = min(nums) for n,v in enumerate(nums): if v+minn<=target: ind.append(n) indv.append(v) for i in ind: if target-nums[i] in indv: indv.remove(nums[i]) ind.remove(i) if target-nums[i] in indv: l = i x = indv.index(target-nums[i]) r = ind[x] return [l,r]
执行用时: 740 ms, 在Two Sum的Python3提交中击败了54.94% 的用户
内存消耗: 7.4 MB, 在Two Sum的Python3提交中击败了79.99% 的用户
自己想的是这个方法,看了答案后,发现一个很神奇的函数 map(),传入的参数是map(function,list),返回值是一个新的list
#1 TowSum Answer
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ mirror = {} for idx, num in enumerate(nums): if num in mirror: return [mirror[num], idx] mirror[target - num] = idx
答案和我的思路是一样的,思维上更高阶,字典还不太熟练的运用.
#2 addTwoNumbers
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ b1 = l1 b2 = l2 b1l=[] b2l=[] r=[] while(b2): b2l.append(str(b2.val)) b2 = b2.next while(b1): b1l.append(str(b1.val)) b1 = b1.next n1 = eval(''.join(b1l[::-1])) n2 = eval(''.join(b2l[::-1])) ans = list(str(n1+n2)) for i in range(len(ans)): r.append(eval(ans.pop(-1))) return r
执行用时: 232 ms, 在Add Two Numbers的Python3提交中击败了4.97% 的用户
内存消耗: 6.7 MB, 在Add Two Numbers的Python3提交中击败了91.98% 的用户
#2
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ add = 0 l3 = ListNode(0) node = l3 while l1 or l2: cur = ListNode(add) if l1: cur.val += l1.val l1 = l1.next if l2: cur.val += l2.val l2 = l2.next add = cur.val // 10 cur.val = cur.val % 10 node.next, node = cur, cur if add: node.next = ListNode(add) return l3.next