标签:input col 链表 http problem 题记 sts one 刷题
160.Intersection of Two Linked Lists
查找并返回AB链表中的交点,若无返回None
方法1:
计算A、B两个链表长度,优先循环长度长的链表,长度差次循环后,依次对比AB
1 class Solution(object): 2 def getIntersectionNode(self, headA, headB): 3 """ 4 :type head1, head1: ListNode 5 :rtype: ListNode 6 """ 7 8 a = headA 9 b = headB 10 anum = 0 11 bnum = 0 12 if not a and not b: return None 13 while a: 14 anum +=1 15 a = a.next 16 while b: 17 bnum +=1 18 b = b.next 19 flag = abs(anum-bnum) 20 if anum>bnum: 21 a = headA 22 b = headB 23 for i in range(flag): 24 a = a.next 25 while a and b: 26 if a.val == b.val: 27 return a 28 a = a.next 29 b = b.next 30 return None 31 else: 32 a = headA 33 b = headB 34 for i in range(flag): 35 b = b.next 36 while a and b : 37 if a.val == b.val: 38 return b 39 a = a.next 40 b = b.next 41 return None 42
方法2:
将AB组合,A循环到链表末尾转至B,B循环到链表末尾转至A,如有相同Node,返回
1 class Solution(object): 2 def getIntersectionNode(self, headA, headB): 3 """ 4 :type head1, head1: ListNode 5 :rtype: ListNode 6 """ 7 8 if not headA or not headB: return None 9 a = headA 10 b = headB 11 flag = 0 12 while flag <=2: 13 if a.val == b.val: 14 return a 15 a = a.next 16 b = b.next 17 if a == None: 18 a = headB 19 flag +=1 20 if b == None: 21 b = headA 22 flag +=1 23 return None
167.Two Sum II - Input array is sorted
给定升序排列数组,寻找和为target的两个数字下标+1(注意:数组中必然存在唯一解)
方法:
设定头指针和尾指针,若和等于target,返回指针+1;若大于target,尾指针前移;否则头指正后移
1 class Solution(object): 2 def twoSum(self, numbers, target): 3 """ 4 :type numbers: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 a, b = 0,len(numbers)-1 9 while a < b: 10 sum1 = numbers[a] + numbers[b] 11 if sum1 == target: 12 return [a+1,b+1] 13 elif sum1 > target: 14 b -=1 15 else: 16 a +=1 17
给定数字n,返回Excel中第n列列号
A-Z对应1-26,递归方法
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ base = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘ if n == 0: return ‘‘ return self.convertToTitle((n-1)/26) + base[(n-1)%26]
标签:input col 链表 http problem 题记 sts one 刷题
原文地址:https://www.cnblogs.com/autoyzz/p/9840200.html