LintCode学习之路
4.丑数II
描述
设计一个算法,找出只含素因子2,3,5 的第 n 小的数。
符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12…
我们可以认为 1 也是一个丑数。
样例
样例 1:
输入:9
输出:10
样例 2:
输入:1
输出:1
class Solution:
"""
@param n: An integer
@return: return a integer as description.
"""
def nthUglyNumber(self, n):
# write your code here
if n == 1:
return 1
res = [1]
p2,p3,p5 = 0,0,0
while len(res)<n:
temp = min(res[p2]*2,res[p3]*3,res[p5]*5)
if temp == res[p2]*2:
p2 +=1
if temp == res[p3]*3:
p3 +=1
if temp == res[p5]*5:
p5 +=1
res.append(temp)
return temp
11. 二叉查找树中搜索区间
描述
给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有 x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: param root: The root of the binary search tree
@param k1: An integer
@param k2: An integer
@return: return: Return all keys that k1<=key<=k2 in ascending order
"""
def searchRange(self, root, k1, k2):
# write your code here
if root is None:
return []
queue = []
queue.append(root)
result = []
while(len(queue)>0):
size=len(queue)
for i in range(size):
node = queue.pop()
if node.val >= k1 and node.val <= k2:
result.append(node.val)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return sorted(result)
17. 子集
给定一个含不同整数的集合,返回其所有的子集。
样例
样例 1:
输入:[0]
输出:
[
[],
[0]
]
样例 2:
输入:[1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
def dfs(nums, index, path, res):
res.append(path)
for i in range(index, len(nums)):
dfs(nums, i + 1, path + [nums[i]], res)
res = []
nums.sort()
dfs(nums, 0, [], res)
return res
60. 搜索插入位置
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
class Solution:
"""
@param A: an integer sorted array
@param target: an integer to be inserted
@return: An integer
"""
def searchInsert(self, A, target):
# write your code here
if len(A) == 0:
return 0
elif A.count(target) > 0:
return A.index(target)
elif target <= A[0]:
return 0
elif target >= A[-1]:
return len(A)
else:
mid = int(len(A)/2)
start = 0
end = len(A)
while start+1<end:
if A[mid]<target:
start = mid
elif A[mid]>target:
end = mid
mid = int((start+end)/2)
return mid+1
85. 在二叉查找树中插入节点
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
样例 1:
输入: tree = {}, node= 1
输出: {1}
样例解释:
在空树中插入一个点,应该插入为根节点。
样例 2:
输入: tree = {2,1,4,3}, node = 6
输出: {2,1,4,3,6}
样例解释:
如下:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if root == None:
return node
temp = root
while temp != node:
if node.val > temp.val:
if temp.right == None:
temp.right = node
temp = temp.right
else:
if temp.left == None:
temp.left = node
temp = temp.left
return root
96. 链表划分
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
样例
样例 1:
输入: list = null, x = 0
输出: null
样例解释:
空链表本身满足要求
样例 2:
输入: list = 1->4->3->2->5->2->null, x = 3
输出: 1->2->2->4->3->5->null
样例解释:
要保持原有的相对顺序。
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
# write your code here
if head is None:
return head
aHead, bHead = ListNode(0), ListNode(0)
small, large = aHead, bHead
while head is not None:
if head.val < x:
small.next = head
small = small.next
else:
large.next = head
large = large.next
head = head.next
large.next = None
small.next = bHead.next
return aHead.next
114. 不同的路径
中文English
有一个机器人的位于一个 m × n 个网格左上角。
机器人每一时刻只能向下或者向右移动一步。机器人试图达到网格的右下角。
问有多少条不同的路径?
样例
样例 1:
输入: n = 1, m = 3
输出: 1
解释: 只有一条通往目标位置的路径。
样例 2:
输入: n = 3, m = 3
输出: 6
解释:
D : Down
R : Right
1) DDRR
2) DRDR
3) DRRD
4) RRDD
5) RDRD
6) RDDR
class Solution:
"""
@param m: positive integer (1 <= m <= 100)
@param n: positive integer (1 <= n <= 100)
@return: An integer
"""
def uniquePaths(self, m, n):
# write your code here
map = [[0 for i in range(n)] for i in range(m)]
num = 0
for i in range(n):
map[0][i] = 1
for i in range(m):
map[i][0] = 1
for i in range(1,m):
for j in range(1,n):
map[i][j] = map[i][j-1] + map[i-1][j]
return map[m-1][n-1]
115. 不同的路径 II
“不同的路径” 的跟进问题:
现在考虑网格中有障碍物,那样将会有多少条不同的路径?
网格中的障碍和空位置分别用 1 和 0 来表示。
样例
样例 1:
输入: [[0]]
输出: 1
样例 2:
输入: [[0,0,0],[0,1,0],[0,0,0]]
输出: 2
解释:
只有 2 种不同的路径.
class Solution:
"""
@param obstacleGrid: A list of lists of integers
@return: An integer
"""
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
map = obstacleGrid
if map[0][0] == 1:
return 0
for i in range(len(map)):
for j in range(len(map[i])):
if i == 0 and j == 0:
map[i][j] = 1
elif i == 0:
if map[i][j] == 1:
map[i][j] = 0
else:
map[i][j] = map[i][j-1]
elif j == 0:
if map[i][j] == 1:
map[i][j] = 0
else:
map[i][j] = map[i-1][j]
else:
if map[i][j] == 1:
map[i][j] = 0
else:
map[i][j] = map[i][j-1] + map[i-1][j]
return map[-1][-1]
133. 最长单词
给一个词典,找出其中所有最长的单词。
样例
样例 1:
输入: {
“dog”,
“google”,
“facebook”,
“internationalization”,
“blabla”
}
输出: [“internationalization”]
样例 2:
输入: {
“like”,
“love”,
“hate”,
“yes”
}
输出: [“like”, “love”, “hate”]
class Solution:
"""
@param: dictionary: an array of strings
@return: an arraylist of strings
"""
def longestWords(self, dictionary):
# write your code here
length = 0
quene = []
for i in dictionary:
if len(i) > length:
if quene == []:
quene.append(i)
length = len(i)
else:
quene = []
quene.append(i)
length = len(i)
elif len(i) == length:
quene.append(i)
length = len(i)
return quene
138. 子数组之和
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
样例
样例 1:
输入: [-3, 1, 2, -3, 4]
输出: [0,2] 或 [1,3]
样例解释:
返回任意一段和为0的区间即可。
样例 2:
输入: [-3, 1, -4, 2, -3, 4]
输出: [1,5]
注意事项
至少有一个子数组的和为 0
class Solution:
"""
@param nums: A list of integers
@return: A list of integers includes the index of the first number and the index of the last number
"""
def subarraySum(self, nums):
# write your code here
if nums == [0]:
return [0,0]
if nums.count(0)>0:
return [nums.index(0),nums.index(0)]
result = []
for i in range(len(nums)):
num = nums[i]
sum = 0
for j in range(i+1,len(nums)):
sum = sum + nums[j]
if sum + num == 0:
result.append([i,j])
break
if result != []:
break
return result[0]
36. 翻转链表 II
翻转链表中第m个节点到第n个节点的部分
样例
例1:
输入: 1->2->3->4->5->NULL, m = 2 and n = 4,
输出: 1->4->3->2->5->NULL.
例2:
输入: 1->2->3->4->NULL, m = 2 and n = 3,
输出: 1->3->2->4->NULL.
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: ListNode head is the head of the linked list
@param m: An integer
@param n: An integer
@return: The head of the reversed ListNode
"""
def reverseBetween(self, head, m, n):
# write your code here
start = head
a = ListNode(0)
a_head = a
temp = ListNode(0)
temp_head =temp
b = ListNode(0)
b_head = b
index = 0
while start:
if index >= m-1 and index <= n-1:
temp.next = ListNode(start.val)
temp = temp.next
if index < m-1:
a.next = ListNode(start.val)
a = a.next
if index > n-1:
b.next = ListNode(start.val)
b = b.next
start = start.next
index += 1
temp_head = temp_head.next
temp_head = self.reverse(temp_head)
a.next = temp_head
b_head = b_head.next
result_head = self.mergeTwoLists(a_head.next,b_head)
return result_head
def mergeTwoLists(self, l1, l2):
head = ListNode(0)
first = head
while l1!=None :
head.next = l1
l1 = l1.next
head = head.next
while l2!=None:
head.next = l2
l2 = l2.next
head = head.next
if l1 != None:
head.next = l1
elif l2 != None:
head.next = l2
return first.next
def reverse(self, head):
# write your code here
start = head
end = None
while start:
temp = start.next
start.next = end
end = start
start = temp
return end
博客围绕Python算法展开,包含丑数II、二叉查找树搜索区间、子集等多道算法题。详细给出各题描述,如找出特定素因子的第n小的数、查找树中特定范围节点值等,并配有样例输入输出,帮助理解算法应用。
1465

被折叠的 条评论
为什么被折叠?



