1、采用hash表的形式解决该问题
题目中的示例:
i | dif | if_true | hash |
0 | dif=target-nums[0]=26-2=24 | false | {2:0} |
1 | dif=26-7=19 | false | {2:0,7:1} |
2 | dif=26-7=19 | false | {2:0,7:2} |
3 | dif=26-11=15 | false | {2:0,7:2,11:3} |
4 | dif=26-15=11 | true | |
5 |
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ nums_hash = {} nums_len = len(nums) for i in range(nums_len): dif = target - nums[i] if dif in nums_hash: return [nums_hash[dif], i] nums_hash[nums[i]] = i print(dif, nums_hash) return [] if __name__ == '__main__': nums = [2,7,7,11,15] target = 26 a = Solution() r = a.twoSum(nums, target) print(r)
2、链表(ListNode)的处理方式
题目中的示例:
步骤 | l1.val | l2.val | carry | pre.val | res.val |
0 | 0 | 0 | 0 | ||
2 | 2 | 5 | 0 | 7 | 7 |
3 | 4 | 6 | 0 | 0 | 0 |
4 | 3 | 4 | 1 | 8 | 8 |
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 :type l3: ListNode ''' carry = 0 res = pre = ListNode(0) while(l1 or l2 or carry): if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next carry, val = divmod(carry, 10) pre.next = pre = ListNode(val) return res.next if __name__ == '__main__': sol = Solution() l1 = ListNode(2) l1.next = l11 = ListNode(4) l11.next = l12 = ListNode(3) l2 = ListNode(5) l2.next = l21 = ListNode(6) l21.next = l22 = ListNode(4) res = sol.addTwoNumbers(l1, l2) while res: print(res.val) res = res.next
class Solution: def lengthOfLongestSubstring(self, s): ''' :type s: str :rtype: int ''' dic = {} star = 0 temp = 0 max_len = 0 for i in range(len(s)): if s[i] in dic: star = max(star, dic[s[i]] + 1) dic[s[i]] = i temp = i + 1 - star max_len = max(temp, max_len) return max_len if __name__ == '__main__': sol = Solution() print(sol.lengthOfLongestSubstring('abcabcdabgf')) print(sol.lengthOfLongestSubstring('pwwkew')) print(sol.lengthOfLongestSubstring('bbbbb')) print(sol.lengthOfLongestSubstring('ababaab')) print(sol.lengthOfLongestSubstring(''))
8.
class Solution: def myAtoi(self, str): dic = {} flag = 1 nums = 0 dic.update({'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}) k = 0 while k < len(str): if str[k] == ' ': if nums==0 and flag == 1: k = k + 1 else: break if str[k] == '-': if nums==0: k = k + 1 flag = -1 else: break if str[k] in dic: nums = nums*10 + dic[str[k]] print(k, str[k]) k = k + 1 continue if (str[k] not in dic) and (str[k] != ' ') and (str[k] != '-'): break return flag * nums if __name__ == '__main__': sol = Solution() print(sol.myAtoi('+'))