给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法1:暴力求解
两层循环嵌套,时间复杂度为O(n²)
代码展示:
python3
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
解法2:hash_map(字典)
一层循环,通过枚举 x,来查找 9-x 是否在 map 中,如果不在,就将它存在map中,如果在,就说明找到了,返回即可,时间复杂度为O(n)
python3
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_map = dict()
for index, x in enumerate(nums):
y = target - x
if y in hash_map:
return [hash_map[y], index]
else:
hash_map[x] = index
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解法:1.判断两链表是否有空链表,若有,直接返回另一个链表。
2.若均不为空,则对应相加即可。
代码展示:
python3
# 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
"""
p = dummy = ListNode(-1)
carry = 0
while l1 and l2:
p.next = ListNode(l1.val + l2.val + carry)
carry =int(p.next.val/10)
p.next.val %= 10
p = p.next
l1 = l1.next
l2 = l2.next
res = l1 or l2
while res:
p.next = ListNode(res.val+ carry)
carry = int(p.next.val/10)
p.next.val %=10
p = p.next
res = res.next
if carry:
p.next = ListNode(1)
return dummy.next
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
解法:遍历字符串中的每一个元素。用一个字典str_dict来存储不重复的字符和字符所在的下标。用变量start存储当前 最近重复字符所在的位置+1
代码展示:
python3
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_len = 0
if s is None or len(s) == 0:
return max_len
str_dict = {}
one_max = 0
start = 0
for i in range(len(s)):
if s[i] in str_dict and str_dict[s[i]] >= start:
start = str_dict[s[i]] + 1
one_max = i - start + 1
str_dict[s[i]] = i
max_len = max(max_len, one_max)
return max_len