lintcode亚麻九题
628.maximum-subtree
Given a binary tree, find the subtree with maximum sum. Return the root of the subtree.
思路很简单,分治就可以
import sys class Solution: # @param {TreeNode} root the root of binary tree # @return {int} the maximum weight node def findSubtree(self, root): # Write your code here self.max_value = -sys.maxint self.max_root = None self.helper(root) return self.max_root def helper(self, root): if not root: return 0 left = self.helper(root.left) right = self.helper(root.right) result = root.val + left + right if result > self.max_value: self.max_value = result self.max_root = root return result
627.Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
大小写敏感。注意是构建,所以统计出每个字符出现次数,然后对偶数求和,如果存在奇数,-1求和,最后+1
class Solution: # @param {string} s a string which consists of lowercase or uppercase letters # @return {int} the length of the longest palindromes that can be built def longestPalindrome(self, s): # Write your code here cache = {} result = 0 for word in s: if word in cache: cache[word] += 1 else: cache[word] = 1 flag = False for key in cache: if cache[key] % 2 == 0: result += cache[key] else: result += cache[key] - 1 flag = True if flag: result += 1 return result
626.Rectangle Overlap
Given two rectangles, find if the given two rectangles overlap or not.
给出的是两个矩形的左上角和右下角,取两个矩形端点比较靠向中心的(交集),判断这个交集是否为空
# Definition for a point. # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b class Solution: # @param {Point} l1 top-left coordinate of first rectangle # @param {Point} r1 bottom-right coordinate of first rectangle # @param {Point} l2 top-left coordinate of second rectangle # @param {Point} r2 bottom-right coordinate of second rectangle # @return {boolean} true if they are overlap or false def doOverlap(self, l1, r1, l2, r2): # Write your code here p1 = Point(max(l1.x, l2.x), min(l1.y, l2.y)) p2 = Point(min(r1.x, r2.x), max(r1.y, r2.y)) if p1.x <= p2.x and p1.y >= p2.y: return True return False
判断重叠很麻烦,但判断不重叠很简单的:
# Definition for a point. # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b class Solution: # @param {Point} l1 top-left coordinate of first rectangle # @param {Point} r1 bottom-right coordinate of first rectangle # @param {Point} l2 top-left coordinate of second rectangle # @param {Point} r2 bottom-right coordinate of second rectangle # @return {boolean} true if they are overlap or false def doOverlap(self, l1, r1, l2, r2): # Write your code here if l1.x > r2.x or l2.x > r1.x: return False if r1.y > l2.y or r2.y > l1.y: return False return True
604.window sum
一个滑动窗遍历数组,求滑动窗的和。
减掉移出的,加入移入的。
class Solution: # @param nums {int[]} a list of integers # @param k {int} size of window # @return {int[]} the sum of element inside the window at each moving def winSum(self, nums, k): # Write your code here result = [] if not nums: return result temp = None for i in range(len(nums) - k + 1): if not result: result.append(sum(nums[i : i + k])) else: result.append(result[-1] - nums[i - 1] + nums[i + k - 1]) return result
616.course-schedule-ii
先修课程,典型的拓扑排序
class Solution: # @param {int} numCourses a total of n courses # @param {int[][]} prerequisites a list of prerequisite pairs # @return {int[]} the course order def findOrder(self, numCourses, prerequisites): # Write your code here nodes = {} for i in range(numCourses): nodes[i] = { "pre" : 0, "after" : [] } for p in prerequisites: nodes[p[1]]["after"].append(p[0]) nodes[p[0]]["pre"] += 1 result = [] queue = [] for key in nodes: if nodes[key]["pre"] == 0: queue.append(key) while queue: key = queue.pop(0) result.append(key) for after in nodes[key]["after"]: nodes[after]["pre"] -= 1 if nodes[after]["pre"] == 0: queue.append(after) if len(result) == numCourses: return result return []
613.High Five
每个学生有两个属性 id
和 scores
。找到每个学生最高的5个分数的平均值。
''' Definition for a Record class Record: def __init__(self, id, score): self.id = id self.score = score ''' import heapq class Solution: # @param {Record[]} results a list of <student_id, score> # @return {dict(id, average)} find the average of 5 highest scores for each person # <key, value> (student_id, average_score) def highFive(self, results): # Write your code here score = {} for r in results: if r.id in score: score[r.id].append(r.score) else: score[r.id] = [r.score] answer = {} for id in score: answer[id] = sum(heapq.nlargest(5, score[id])) / 5.0 return answer
612.k closest points
找到离目标点最近的k个点。heapq + functools.cmp_to_key
# Definition for a point. # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b import heapq from functools import cmp_to_key class Solution: # @param {Pint[]} points a list of points # @param {Point} origin a point # @param {int} k an integer # @return {Pint[]} the k closest points def kClosest(self, points, origin, k): # Write your code here def cmp(x1, x2): distance = ((x1.x - origin.x) ** 2 + (x1.y - origin.y) ** 2) \ - ((x2.x - origin.x) ** 2 + (x2.y - origin.y) ** 2) if distance < 0: return -1 elif distance == 0: if x1.x < x2.x: return -1 elif x1.x == x2.x: if x1.y < x2.y: return -1 elif x1.y == x2.y: return 0 else: return 1 else: return 1 else: return 1 return heapq.nsmallest(k, points, key = cmp_to_key(cmp))
105.Copy List with Random Pointer
带有随机指针的链表,做一次完全的拷贝。
下次尝试O(1)空间复杂度
# Definition for singly-linked list with a random pointer. # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # @param head: A RandomListNode # @return: A RandomListNode def copyRandomList(self, head): # write your code here nodes = {} # copy nodes cur = head while cur: nodes[cur.label] = RandomListNode(cur.label) cur = cur.next # copy next cur = head while cur.next: nodes[cur.label].next = nodes[cur.next.label] cur = cur.next # copy random cur = head while cur: if cur.random: nodes[cur.label].random = nodes[cur.random.label] cur = cur.next return nodes[head.label]
629.minimum spanning tree
最小生成树,Prim算法思想类似于BFS
''' Definition for a Connection class Connection: def __init__(self, city1, city2, cost): self.city1, self.city2, self.cost = city1, city2, cost ''' import heapq class Solution: # @param {Connection[]} connections given a list of connections # include two cities and cost # @return {Connection[]} a list of connections from results def lowestCost(self, connections): # Write your code here heap = [] result = [] cities = {} cons = {} for c in connections: cons[(c.cost, c.city1, c.city2)] = c cities.setdefault(c.city1, []).append((c.cost, c.city1, c.city2)) cities.setdefault(c.city2, []).append((c.cost, c.city1, c.city2)) visited = set([connections[0].city1]) heap = [c for c in cities[connections[0].city1]] heapq.heapify(heap) while heap: c = heapq.heappop(heap) while c[1] in visited and c[2] in visited and heap: c = heapq.heappop(heap) if c[1] in visited and c[2] in visited: break result.append(c) new_city = c[1] if c[1] not in visited else c[2] visited.add(new_city) for new_c in cities[new_city]: if new_c[1] in visited and new_c[2] in visited: continue heapq.heappush(heap, new_c) result.sort() return [cons[r] for r in result] if len(visited) == len(cities) else []