56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
思路:先按start排序,再合并
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) == 0:
return []
intervals.sort(key = lambda x : x.start)
ans = [intervals[0]]
for interval in intervals[1: ]:
if ans[-1].end < interval.start:
ans.append(interval)
elif ans[-1].end < interval.end:
ans[-1].end = interval.end
return ans
Beat 100.0% python3 2018-05-20
5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
思路:从每一个位置往两边扩展,扩展方式有两种:1)axa, 2) axxa
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def expandPalindrome(left, right):
while left >= 0 and right < length and s[left] == s[right]:
left -= 1
right += 1
return left+1, right-1
start, end = 0, 0
length = len(s)
for i in range(0, length):
sp, ep = expandPalindrome(i, i)
if ep - sp > end - start:
start, end = sp, ep
sp, ep = expandPalindrome(i, i+1)
if ep - sp > end - start:
start, end = sp, ep
return s[start : end+1]
Beat 73.90% python3 2019-05-20
优化:以每个位置为中心,按两种方式判断比当前找到的最长的回文串长的串是否是回文串
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def isPalindrome(ss):
return ss == ss[::-1]
end, max_len = 0, 1
length = len(s)
for i in range(1, length):
if i - max_len >= 0 and isPalindrome(s[i-max_len : i+1]):
max_len += 1
end = i
elif i - max_len >= 1 and isPalindrome(s[i-max_len-1 : i+1]):
max_len += 2
end = i
return s[end-max_len+1 : end+1]
Beat 99.40% python3 2019-05-20
17. Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
思路:DFS
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
dict = {
'2' : "abc",
'3' : "def",
'4' : "ghi",
'5' : "jkl",
'6' : "mno",
'7' : "pqrs",
'8' : "tuv",
'9' : "wxyz"
}
def dfs(current, start):
if start == length:
ans.append(current)
return
for c in dict[digits[start]]:
dfs(current+c, start+1)
length = len(digits)
if length == 0:
return []
ans = []
dfs('', 0)
return ans
Beat 97.83% python3 2019-05-21
19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
思路:两个指针,第一个先走n步,然后两个同时走,第一个走到尾,此时的二个为倒数第n个位置。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first, second = head, head
for i in range(n):
first = first.next
pre = None
while first != None:
first = first.next
pre = second
second = second.next
if pre == None:
head = head.next
else:
pre.next = second.next
return head
Beat 99.91% python3 2018-05-21
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
思路:使用一个list保存所有node,排序,再生成链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
from operator import attrgetter
nodes = []
for head in lists:
while head is not None:
nodes.append(head)
head = head.next
if len(nodes) == 0:
return None
nodes = sorted(nodes, key = attrgetter('val'))
head = nodes[0]
tail = head
for n in nodes[1 :]:
tail.next = n
tail = n
return head
Beat 99.36% python3 2018-05-22