Zhuanli&Blog


  • 首页

  • 标签

  • 分类

  • 归档

leetcode 213. 打家劫舍 II

发表于 2018-06-27 | 分类于 leetcode

你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。

示例 1:

输入: [2,3,2]
输出: 3
解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。

示例 2:

输入: [1,2,3,1]
输出: 4
解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:return 0
if len(nums) <= 3:return max(nums)
dp1 = nums[:-1]
dp1[1] = max(nums[0],nums[1])
dp2 = nums[1:]
dp2[1] = max(nums[1],nums[2])
for i in range(2,len(nums)-1):
dp1[i] = max(dp1[i-2] + nums[i],dp1[i-1])
dp2[i] = max(dp2[i-2] + nums[i+1],dp2[i-1])
return max(dp1[-1],dp2[-1])

leetcode 337. 打家劫舍 III

发表于 2018-06-26 | 分类于 leetcode

小偷又发现一个新的可行窃的地点。 这个地区只有一个入口,称为“根”。 除了根部之外,每栋房子有且只有一个父房子。 一番侦察之后,聪明的小偷意识到“这个地方的所有房屋形成了一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。

在不触动警报的情况下,计算小偷一晚能盗取的最高金额。

示例 1:


3
/ \
2 3
\ \
3 1

能盗取的最高金额 = 3 + 3 + 1 = 7.

示例 2:


3
/ \
4 5
/ \ \
1 3 1

能盗取的最高金额 = 4 + 5 = 9.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
'''
return [i, j] i is max value include root, j is max value exclude root
'''
def helper(self, root):
# corner case
if root == None:
return [0, 0]
if root.left == None and root.right == None:
return [root.val, 0]
left = self.helper(root.left)
right = self.helper(root.right)
'''
when root is included, then we only add left and right node's max value which does not include themselves
when root is not included, then we should add max of left and max of right, i.e. consider situations that either include left node or not include left node, choose the larger value
'''
return [root.val+left[1]+right[1], max(left)+max(right)]
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return max(self.helper(root))
  • a clear solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None


'''
Let

f1(node) be the value of maximum money we can rob from the subtree with node as root ( we can rob node if necessary).

f2(node) be the value of maximum money we can rob from the subtree with node as root but without robbing node.

Then we have

f2(node) = f1(node.left) + f1(node.right) and

f1(node) = max( f2(node.left)+f2(node.right)+node.value, f2(node) ).

'''
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.robDFS(root)[1];
def robDFS(self,node):
if node is None:
return (0,0)
l = self.robDFS(node.left)
r = self.robDFS(node.right)
return (l[1] + r[1], max(l[1] + r[1], l[0] + r[0] + node.val))

leetcode 338. Bit位计数

发表于 2018-06-25 | 分类于 leetcode

给定一个非负整数 num。 对于范围 0 ≤ i ≤ num 中的每个数字 i ,计算其二进制数中的1的数目并将它们作为数组返回。

示例:
比如给定 num = 5 ,应该返回 [0,1,1,2,1,2].

进阶:

  • 给出时间复杂度为O(n * sizeof(integer)) 的解答非常容易。 但是你可以在线性时间O(n)内用一次遍历做到吗?
  • 要求算法的空间复杂度为O(n)。
  • 你能进一步完善解法吗? 在c ++或任何其他语言中不使用任何内置函数(如c++里的 __builtin_popcount)来执行此操作。

  • my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
def countv(v):
vlen = 0
while v:
v &= (v-1)
vlen += 1
return vlen
res = [0]*(num+1)
for i in range(0,num+1,4):
vlen = countv(i)
res[i] = vlen
if i + 1 > num:break
res[i+1] = vlen+1
if i + 2 > num:break
res[i+2] = vlen+1
if i + 3 > num:break
res[i+3] = vlen+2
return res
  • a faster solution
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
if num == 0:return [0]
if num == 1:return [0,1]
res = [0]*(num+1)
res[1] = 1
for i in range(2,num+1):
res[i] = res[i>>1] + i%2
return res

leetcode 341. Flatten Nested List Iterator

发表于 2018-06-22 | 分类于 leetcode

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list – whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:
Given the list [1,[4,[6]]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):

def __init__(self, nestedList):
self.stack = [[nestedList, 0]]

def next(self):
self.hasNext()
nestedList, i = self.stack[-1]
self.stack[-1][1] += 1
return nestedList[i].getInteger()

def hasNext(self):
s = self.stack
while s:
nestedList, i = s[-1]
if i == len(nestedList):
s.pop()
else:
x = nestedList[i]
if x.isInteger():
return True
s[-1][1] += 1
s.append([x.getList(), 0])
return False
# class NestedIterator(object):

# def __init__(self, nestedList):
# """
# Initialize your data structure here.
# :type nestedList: List[NestedInteger]
# """
# self._ind = 0
# self._nest = self._flat(nestedList)

# def _flat(self,nestlist):
# res = []
# stack = [(nestlist,0)]
# while stack:
# nest,i = stack.pop()
# if i >= len(nest):
# continue
# tmp = nest[i]
# stack.append((nest,i+1))
# if tmp.isInteger():
# res.append(tmp)
# else:
# stack.append((tmp,0))
# return res

# def next(self):
# """
# :rtype: int
# """
# i = self._ind
# self._ind += 1
# return self._nest[i]



# def hasNext(self):
# """
# :rtype: bool
# """
# return self._ind < len(self._nest)

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

leetcode 343. 整数拆分

发表于 2018-06-21 | 分类于 leetcode

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

例如,给定 n = 2,返回1(2 = 1 + 1);给定 n = 10,返回36(10 = 3 + 3 + 4)。

注意:你可以假设 n 不小于2且不大于58。

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if n == 2:return 1
elif n == 3:return 2
elif n%3 == 0:return 3**(n/3)
elif n%3 == 1:return 4*3**((n-4)/3)
else:return 2*3**(n/3)

数组循环移位

发表于 2018-06-21 | 分类于 算法

字符串或数组的翻转,比如输入’hello’, return ‘olleh’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
slist = list(s)
def reverse(str1,index1,index2):
while index1 < index2:
str1[index1],str1[index2]=str1[index2],str1[index1]
index1 += 1
index2 -= 1
reverse(slist,0,len(slist)-1)
return ''.join(slist)

如果要求把字符串或数组向左或右移动k位,也可以通过reverse的方法做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def reverseString(self, s,k):
"""
:type s: str
:rtype: str
"""
slist = list(s)
N = len(s)
k %= N
def reverse(str1,index1,index2):
while index1 < index2:
str1[index1],str1[index2]=str1[index2],str1[index1]
index1 += 1
index2 -= 1
reverse(slist,0,N-k-1)
reverse(slist,N-k,N-1)
reverse(slist,0,N-1)
return ''.join(slist)

leetcode 347. Top K Frequent Elements

发表于 2018-06-20 | 分类于 leetcode

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import heapq
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
d = {}
for i in nums:
if i not in d:d[i] = 1
else: d[i] += 1

return heapq.nlargest(k,d,key=lambda x:d[x])

leetcode 355. Design Twitter

发表于 2018-06-20 | 分类于 leetcode

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user’s news feed. Your design should support the following methods:

  1. postTweet(userId, tweetId): Compose a new tweet.
  2. getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user’s news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. unfollow(followerId, followeeId): Follower unfollows a followee.

Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import collections
class Twitter(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.follows = collections.defaultdict(set)
self.usertwitter = collections.defaultdict(list)
self.order = 0

def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.usertwitter[userId] += (self.order, tweetId),
self.order -= 1


def getNewsFeed(self, userId):
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
:type userId: int
:rtype: List[int]
"""
tw = sorted(tw for i in self.follows[userId] | {userId} for tw in self.usertwitter[i])[:10]
return [news for i, news in tw]


def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.follows[followerId].add(followeeId)

def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.follows[followerId].discard(followeeId)

leetcode 363. Max Sum of Rectangle No Larger Than K

发表于 2018-06-19 | 分类于 leetcode

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.

Example:

Given matrix = [
  [1,  0, 1],
  [0, -2, 3]
]
k = 2

The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution(object):
def maxSubArray(self,nums,k):

cumset=[]
cumset.append(0)
maxsum=-1<<32
cursum=0
for i in range(len(nums)):
cursum+=nums[i]
# find the lower bound of the index
idx=bisect.bisect_left(cumset,cursum-k)
# find max in sum[right]-sum[left]<=k
if 0<=idx<len(cumset):
maxsum=max(maxsum,cursum-cumset[idx])
# using insort instead of append since bisect_left reason
bisect.insort(cumset,cursum)
return maxsum
def maxSumSubmatrix(self,matrix, k):

if not matrix or not matrix[0]:
return 0
row,col=len(matrix),len(matrix[0])
res=-(1<<32)
for left in range(col):
cursums=[0 for _ in range(row)]
right=left
while right<col:
for i in range(row):
cursums[i]+=matrix[i][right]
curarrmax=self.maxSubArray(cursums,k)
res=max(res,curarrmax)
right+=1

return res

git+hexo博客绑定域名

发表于 2018-06-19 | 分类于 tools
  1. 买一个域名,在你的域名管理有一个解析的选项,添加两条记录类型为CNAME的解析,一条主机记录为@,一条主机记录为www,记录值都为你的格式为xxxx.github.io的地址。
  2. 在你的本地hexo博客文件的source文件夹下创建一个CNAME文件,记住不要有文件后缀名。编辑CNAME文件,里面写你在第一步申请的域名,例如xxxx.cn,记住不要有www,不要有http://。

  3. 在你本地博客文件里运行hexo g,再运行hexo d。

  4. 访问你的域名
1…111213…20

zhuanli

194 日志
9 分类
41 标签
GitHub
© 2018 — 2019 zhuanli
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4