Zhuanli&Blog


  • 首页

  • 标签

  • 分类

  • 归档

leetcode 299. 猜数字游戏

发表于 2018-08-09 | 分类于 leetcode

你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。

请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。

请注意秘密数字和朋友的猜测数都可能含有重复数字。

示例 1:

输入: secret = "1807", guess = "7810"

输出: "1A3B"

解释: 1 公牛和 3 奶牛。公牛是 8,奶牛是 0, 1 和 7。

示例 2:

输入: secret = "1123", guess = "0111"

输出: "1A1B"

解释: 朋友猜测数中的第一个 1 是公牛,第二个或第三个 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
import collections
class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
n=len(secret)
cntA = 0
cnt = 0
for i in range(n):
if secret[i] == guess[i]:
cntA += 1
d = collections.Counter(secret)
for s in guess:
if s in secret:
d[s] -= 1

for key in d.keys():
if d[key] >= 0:
cnt += int(d[key])
cnt = n -cnt
return str(cntA)+'A'+str(cnt-cntA)+'B'

leetcode 295. 数据流的中位数

发表于 2018-08-08 | 分类于 leetcode

中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。

例如,

[2,3,4] 的中位数是 3

[2,3] 的中位数是 (2 + 3) / 2 = 2.5

设计一个支持以下两种操作的数据结构:

  • void addNum(int num) - 从数据流中添加一个整数到数据结构中。
  • double findMedian() - 返回目前所有元素的中位数。

示例:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 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
import bisect
class MedianFinder(object):

def __init__(self):
"""
initialize your data structure here.
"""
self.res = []

def addNum(self, num):
"""
:type num: int
:rtype: void
"""
bisect.insort_left(self.res,num)

def findMedian(self):
"""
:rtype: float
"""
n = len(self.res)
if n%2 == 0:
return (self.res[n//2]+self.res[n//2-1])/2
else:return self.res[n//2]

leetcode 284. 顶端迭代器

发表于 2018-08-07 | 分类于 leetcode

给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 – 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。

示例:

假设迭代器被初始化为列表 [1,2,3]。

调用 next() 返回 1,得到列表中的第一个元素。
现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false。
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
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """

class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iter = iterator
self.pee = self.iter.next() if self.iter.hasNext() else None

def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.pee

def next(self):
"""
:rtype: int
"""
res = self.pee
self.pee = self.iter.next() if self.iter.hasNext() else None
return res

def hasNext(self):
"""
:rtype: bool
"""
return self.pee is not None

# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].

leetcode 287. 寻找重复数

发表于 2018-08-05 | 分类于 leetcode

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:

输入: [1,3,4,2,2]
输出: 2

示例 2:

输入: [3,1,3,4,2]
输出: 3

说明:

  • 不能更改原数组(假设数组是只读的)。
  • 只能使用额外的 O(1) 的空间。
  • 时间复杂度小于 O(n2) 。
  • 数组中只有一个重复的数字,但它可能不止重复出现一次。
1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
tmp = 0
for i in sorted(nums):
if tmp == i:
return i
tmp = i

leetcode 282. 给表达式添加运算符

发表于 2018-08-03 | 分类于 leetcode

给定一个仅包含数字 0-9 的字符串和一个目标值,在数字之间添加二元运算符(不是一元)+、- 或 * ,返回所有能够得到目标值的表达式。

示例 1:

输入: num = "123", target = 6
输出: ["1+2+3", "1*2*3"] 

示例 2:

输入: num = "232", target = 8
输出: ["2*3+2", "2+3*2"]

示例 3:

输入: num = "105", target = 5
输出: ["1*0+5","10-5"]
示例 4:
输入: num = "00", target = 0
输出: ["0+0", "0-0", "0*0"]
示例 5:
输入: num = "3456237490", target = 9191
输出: []
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 addOperators(self, num, target):
def dfs(remain, curr_str, curr, prev):
if not remain and curr == target:
res.append(curr_str)

for i in range(1, len(remain) + 1):
if len(curr_str) == 0: #avoid generate str begin with +-*
if not (i > 1 and remain[0] == '0'): # avoid '0X' case be counted
dfs(remain[i:], remain[:i], int(remain[:i]), int(remain[:i]))
else:
if not (i > 1 and remain[0] == '0'):
dfs(remain[i:], curr_str + '+' + remain[:i], curr + int(remain[:i]), int(remain[:i]))
dfs(remain[i:], curr_str + '-' + remain[:i], curr - int(remain[:i]), -int(remain[:i]))
# need take extra care for '*' case, a+b*c = a+b-b+b*c
dfs(remain[i:], curr_str + '*' + remain[:i], curr - prev + prev * int(remain[:i]), prev * int(remain[:i]))

res = []
dfs(num, '', 0, 0)
return res
print(Solution().addOperators('105',5))

朱安里是个大坑比

发表于 2018-08-02 | 分类于 c

现在《王者荣耀》游戏依然火爆,当然有玩的好的,也有一群坑货一般的队友,都爱说:不怕神一样的对手,就怕猪一样的队友。遇到坑队友,也只能是无奈,但是有些人气不过啊,在游戏里觉得自己是坑了,被队友喷了,就像下面这样去回击,啧啧啧,不知道逞一时之快,会不会被喷啊~~

leetcode 273. 整数转换英文表示

发表于 2018-08-02 | 分类于 leetcode

将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。

示例 1:

输入: 123
输出: "One Hundred Twenty Three"

示例 2:

输入: 12345
输出: "Twelve Thousand Three Hundred Forty Five"

示例 3:

输入: 1234567
输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

示例 4:

输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
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
class Solution(object):

def __init__(self):
self.lessThan20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
self.tens = ["", "Ten", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
self.thousands = ["", "Thousand", "Million", "Billion"]


def numberToWords(self, num):
if num == 0:
return "Zero"
res = ""
for i in range(len(self.thousands)):
if num % 1000 != 0:
res = self.helper(num % 1000) + self.thousands[i] + " " + res
num /= 1000
return res.strip()


def helper(self, num):
if num == 0:
return ""
elif num < 20:
return self.lessThan20[num] + " "
elif num < 100:
return self.tens[num/10] + " " + self.helper(num % 10)
else:
return self.lessThan20[num/100] + " Hundred " + self.helper(num % 100)

leetcode 264. 丑数 II

发表于 2018-08-01 | 分类于 leetcode

编写一个程序,找出第 n 个丑数。

丑数就是只包含质因数 2, 3, 5 的正整数。

示例:

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

说明:

  • 1 是丑数。
  • n 不超过1690。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object): # 264. Ugly Number II
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
dp = [1 for i in range(n)]
i2, i3, i5 = 0, 0, 0
for i in range(1,n):
n2, n3, n5 = dp[i2]*2, dp[i3]*3, dp[i5]*5
dp[i] = min(n2, n3, n5)
if dp[i] == n2: i2 += 1
if dp[i] == n3: i3 += 1
if dp[i] == n5: i5 += 1
# print(dp)
return dp[-1]

leetcode 262. Trips and Users

发表于 2018-07-31 | 分类于 mysql

The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’).

+----+-----------+-----------+---------+--------------------+----------+
| Id | Client_Id | Driver_Id | City_Id |        Status      |Request_at|
+----+-----------+-----------+---------+--------------------+----------+
| 1  |     1     |    10     |    1    |     completed      |2013-10-01|
| 2  |     2     |    11     |    1    | cancelled_by_driver|2013-10-01|
| 3  |     3     |    12     |    6    |     completed      |2013-10-01|
| 4  |     4     |    13     |    6    | cancelled_by_client|2013-10-01|
| 5  |     1     |    10     |    1    |     completed      |2013-10-02|
| 6  |     2     |    11     |    6    |     completed      |2013-10-02|
| 7  |     3     |    12     |    6    |     completed      |2013-10-02|
| 8  |     2     |    12     |    12   |     completed      |2013-10-03|
| 9  |     3     |    10     |    12   |     completed      |2013-10-03| 
| 10 |     4     |    13     |    12   | cancelled_by_driver|2013-10-03|
+----+-----------+-----------+---------+--------------------+----------+

The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of (‘client’, ‘driver’, ‘partner’).

+----------+--------+--------+
| Users_Id | Banned |  Role  |
+----------+--------+--------+
|    1     |   No   | client |
|    2     |   Yes  | client |
|    3     |   No   | client |
|    4     |   No   | client |
|    10    |   No   | driver |
|    11    |   No   | driver |
|    12    |   No   | driver |
|    13    |   No   | driver |
+----------+--------+--------+

Write a SQL query to find the cancellation rate of requests made by unbanned users between Oct 1, 2013 and Oct 3, 2013. For the above tables, your SQL query should return the following rows with the cancellation rate being rounded to two decimal places.

+------------+-------------------+
|     Day    | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 |       0.33        |
| 2013-10-02 |       0.00        |
| 2013-10-03 |       0.50        |
+------------+-------------------+
1
2
3
4
5
6
7
# Write your MySQL query statement below
SELECT Request_at as Day,
ROUND(COUNT(IF(Status != 'completed', TRUE, NULL)) / COUNT(*), 2) AS 'Cancellation Rate'
FROM Trips
WHERE (Request_at BETWEEN '2013-10-01' AND '2013-10-03')
AND Client_id NOT IN (SELECT Users_Id FROM Users WHERE Banned = 'Yes'and Role='client')
GROUP BY Request_at;

leetcode 260. 只出现一次的数字 III

发表于 2018-07-30 | 分类于 leetcode

给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。

示例 :

输入: [1,2,1,3,2,5]
输出: [3,5]

注意:

  • 结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
  • 你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
d = {}
res = []
for i in nums:
d[i] = d.get(i,0)+1
for key in d.keys():
if d[key] == 1:
res.append(key)
return res
1…789…20

zhuanli

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