Zhuanli&Blog


  • 首页

  • 标签

  • 分类

  • 归档

leetcode 430. Flatten a Multilevel Doubly Linked List

发表于 2019-01-09 | 分类于 leetcode

题目链接:leetcode

思路:
链表

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
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
stack,cur = [],head
while cur:
if cur.child:
if cur.next:
stack.append(cur.next)
cur.next,cur.child.prev,cur.child = cur.child,cur,None
if not cur.next and len(stack) >0:
tmp = stack.pop()
tmp.prev,cur.next = cur,tmp
cur = cur.next
return head

leetcode 143. Reorder List

发表于 2019-01-02 | 分类于 leetcode

题目链接:leetcode

思路:
链表

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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head:return None
slow = node = head
fast = slow.next
stack=[]
while fast and fast.next:
slow = slow.next
fast = fast.next.next
new_slow = slow.next
slow.next = None
while new_slow:
stack.append(new_slow)
new_slow = new_slow.next
while node:
next_node = node.next
if stack:
node.next=stack.pop()
node.next.next = next_node
node = next_node

leetcode 139. Word Break

发表于 2018-12-29 | 分类于 leetcode

题目链接:leetcode

思路:
用递归做会超时,发现可以分解为更小的问题,用动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
d = {}
dp = [False]*len(s)
for word in wordDict:
if word not in d:
d[word] = 1
dp[0] = True if s[0] in d else False
for i in range(1,len(s)):
if s[:i+1] in d:
dp[i] = True
continue
for j in range(i):
if dp[j] and s[j+1:i+1] in d:
dp[i] = True
break
return dp[-1]

leetcode 138. Copy List with Random Pointer

发表于 2018-12-28 | 分类于 leetcode

题目链接:leetcode

思路:
遍历原链表,生成新链表

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
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None

class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None

p = head
newhead = q = RandomListNode(head.label)

while p:
q.next = None if not p.next else RandomListNode(p.next.label)
q.random = None if not p.random else RandomListNode(p.random.label)
p = p.next
q = q.next
return newhead

leetcode 137. Single Number II

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

题目链接:leetcode

思路:
使用xor异或的性质可以常数空间复杂度解决问题。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ones = twos = threes= 0
for num in nums:
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
return ones
print(Solution().singleNumber([1,1,1,2,2,2,3]))

leetcode 134. Gas Station

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

题目链接:leetcode

思路:
贪婪

1
2
3
4
5
6
7
8
9
class Solution(object):
def canCompleteCircuit(self, gas, cost):
n = len(gas)
dp = [gas[0] - cost[0]]
for i in range(1,n):
dp.append(dp[-1] + gas[i] - cost[i])
if dp[-1] < 0:
return -1
return (dp.index(min(dp)) + 1 )%n

一个更清晰的solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
start, cur_sum, total_sum = 0, 0, 0

for i in range(len(gas)):
diff = gas[i]-cost[i]
cur_sum += diff
total_sum += diff

if cur_sum < 0:
start = i+1
cur_sum = 0

if total_sum >= 0:
return start
return -1

leetcode 133. 克隆图

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

题目链接:leetcode

思路:
bfs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from collections import deque
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if node == None:
return
root = UndirectedGraphNode(node.label)
q = deque([(node, root)]) # node to complete neighbors
visited = set()
while q:
n, tobe = q.popleft()
visited.add(n)
for neighbor in n.neighbors:
neighbor_tobe = UndirectedGraphNode(neighbor.label)
tobe.neighbors.append(neighbor_tobe)
if neighbor not in visited:
q.append((neighbor, neighbor_tobe))
return root

leetcode 131. Palindrome Partitioning

发表于 2018-12-24 | 分类于 leetcode

题目链接:leetcode

思路:
回溯

class Solution:
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        self.s =s

        def dfs(s,res,tmp):
            if not s:
                res.append(tmp[:])
                return
            for i in range(1,len(s)+1):
                stmp = s[:i]
                if stmp == stmp[::-1]:
                    #这行代码等价于
                    #tmp.append(stmp)
                    #dfs(s[i:],res,tmp)
                    #tmp.pop()
                    dfs(s[i:],res,tmp+[stmp])
        res=[]
        dfs(self.s,res,[])
        return res

docker 制作镜像

发表于 2018-12-22 | 分类于 tools

1 手动制作

1
2
3
4
5
6
7
8
9
docker run -itd XXX
docker attach xxx
ctrl +p +q 不关闭容器 从新定位到本地目录
docker cp /Users/xx a5:/usr/xx
docker commit a5 java
把镜像导出为压缩文件
docker save -o service.tar a5
ocker load -i service.tar
docker tag fd12 java:zhuanli

2 Dockerfile

1
2
3
FROM java
MAINTAINER zhuanli
COPY xx /usr/xx

运行

1
docker build -t java:zhuanli  .

3 docker-compose.yml

1
2
3
4
5
6
7
8
version: "3" 
services:
sharelist:
image: java
volumes:
- /home/zhuanli/java:/app/cache
ports:
- "33001:33001"

memcheck检测内存的原理

发表于 2018-12-22 | 分类于 tools

原始信息:http://valgrind.org/docs/manual/mc-manual.html#mc-manual.machine

基本原理:

memcheck实现了一个仿真的CPU,被监控的程序被这个仿真CPU解释执行,从而有机会在所有的内存读写指令发生的时候,检测地址的合法性和读操作的合法性。

一,如何知道那些地址是合法的(内存已分配)?

维护一张合法地址表(Valid-address (A) bits),当前所有可以合法读写(已分配)的地址在其中有对应的表项。该表通过以下措施维护

全局数据(data, bss section)--在程序启动的时候标记为合法地址

局部变量--监控sp(stack pointer)的变化,动态维护

动态分配的内存--截获 分配/释放 内存的调用 :malloc, calloc, realloc, valloc, memalign, free, new, new[], delete and delete[]

系统调用--截获mmap映射的地址

其他--可以显示知会memcheck某地字段是合法的

二,如何知道某内存是否已经被赋值?

维护一张合法值表(Valid-value (V) bits),指示对应的bit是否已经被赋值。因为虚拟CPU可以捕获所有对内存的写指令,所以这张表很容易维护。

局限:

-memcheck无法检测global和stack上的内存溢出,因为溢出的地方也在Valid-address (A) bits中。这是由memcheck 的工作原理决定的。

-慢,20到30倍,被虚拟CPU解释一遍,当然慢

-内存占用高,因为要维护两张表格,而这两张表的维度正比于程序的内存

12…20

zhuanli

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