f***c 发帖数: 338 | 1 Is it true?
今天刚挂了狗狗的电面。一个超级简单的问题(现在看来),就是因为当时脑子突然短路
,就给整砸了。还是得走出去,多练呀。
浪费这个狗狗的机会太可惜后悔了。
面的是TE,说一下具体的题目。
白板测试,用的googledoc,给一个输入,文件或终端,输出含有abc def的line
其实就是一个*nix 下grep就够了,我还在那里想用python的re来处理。要是把自己的
函数搞对了还好,还一紧张搞错了。阿Q一下,当时想的时候,think loud了要用grep
的。就是脑子突然短路,陷在def patternMatch上出不来了。
第一个白板就挂了,对方对俺的coding已经放弃了。
然后就是一些按给定的情形,设计test case。有印象的是一个判断三个数能否构成三
角形的题目。别的没太大印象了。
再谴责一下自己,继续准备下一个机会。 |
|
i**9 发帖数: 351 | 2 quick code review:
if variable != None -- > if variable
if variable== None ---> if !variable
python method name
def methodName ---> def method_name: |
|
t**r 发帖数: 3428 | 3 # In this solution as soon as we find a 1, we replace
# all the elements in the shape with 2 to avoid double
# counting the 1s. Otherwise, it's simple iteration.
def count_shapes(m):
num_shapes = 0
for r in range(len(m)):
for c in range(len(m[0])):
if m[r][c] == 1:
fill_shape_with_twos(m, r, c)
num_shapes += 1
# restore the original values
for r in range(len(m)):
for c in range(len(m[0])):
m[r][c] = m[r][c] ... 阅读全帖 |
|
t**r 发帖数: 3428 | 4 # In this solution as soon as we find a 1, we replace
# all the elements in the shape with 2 to avoid double
# counting the 1s. Otherwise, it's simple iteration.
def count_shapes(m):
num_shapes = 0
for r in range(len(m)):
for c in range(len(m[0])):
if m[r][c] == 1:
fill_shape_with_twos(m, r, c)
num_shapes += 1
# restore the original values
for r in range(len(m)):
for c in range(len(m[0])):
m[r][c] = m[r][c] ... 阅读全帖 |
|
t********n 发帖数: 611 | 5 Thanks!
My answer in ruby:
require 'set'
def sum_3(arr, k)
check = arr.to_set
result = Set.new
arr.each do |m|
arr.each do |n|
target = k - m -n
if check.include?(target)
result.add([m, n, target].to_set)
end
end
end
result
end
def restore(my_set, k)
result = []
my_set.each do |s|
if s.length == 3
result << s.to_a
elsif s.length == 2
arr = s.to_a
arr << (k - arr[0] - arr[1])
result << arr
else
result << (s.... 阅读全帖 |
|
t********n 发帖数: 611 | 6 还是不够快的问题,自己机器上测试结果正确,用了BFS and DFS,不知道还能怎样改
进,请牛牛们指教!
Python code:
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return a list of lists of string
def findLadders(self, start, end, dict):
def buildPath(end, start, path= []):
path += [end]
if end == start:
path.reverse()
result.append(path)
else:
for p in parents[end]:
... 阅读全帖 |
|
t********n 发帖数: 611 | 7 过了, 参考了某位高人的代码,每次找下级词汇前,把这一级从字典里删除,立刻快
了很多。
Code:
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return a list of lists of string
def findLadders(self, start, end, dict):
def buildPath(end, start, path= []):
# print
# print "path at beginning:", path
path += [end]
if end == start:
path.reverse()
result.append(path)
else:
... 阅读全帖 |
|
d****n 发帖数: 397 | 8 我一开始也没过。但是注意到不是所有parent都要记录。BFS里面同级之间的parent不
要记录,就可以了。
这是我写的python 解法。
#! /usr/bin/python
import collections
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return a list of lists of string
def findLadders(self, start, end, dict):
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z']
dict = dict | set([end])
dict = dict | set([start])
... 阅读全帖 |
|
f**********t 发帖数: 1001 | 9 class CompanyDB:
def __init__(self, fname):
self.industries = defaultdict(set)
self.companies = defaultdict(set)
fp = open(fname);
for line in fp.readlines:
items = line.split('|')
if len(items) < 3:
continue
if items[0] == "industry":
self.industries[items[2].strip()].add(items[1].strip())
elif items[0] == "company":
self.companies[items[2].strip()].add(items[1].st... 阅读全帖 |
|
l***s 发帖数: 15 | 10 my accepted codes. seems different algorithm than the one found online
class Solution:
# @return a string
def longestPalindrome(self, s):
le = len(s)
if not s:
return ''
table=[] #record longest so far and longest ending at i
table.append(((0,0), 1))
for i in xrange(1,le):
curind=table[-1][0]
lastsofar=curind[1]-curind[0]+1
lastending=table[-1][1]
for j in xrange(i-lastending-1, i+1):... 阅读全帖 |
|
D****3 发帖数: 611 | 11
我原来给的解还能refactor一下。给个新的吧:
--------
其实这个java解本身就不是最优的。因为跑了很多根本没可能是最长susbtring的解。
Leetcode对python的速度比较高。我在你的算法上改进了下:
从中间开始选对称轴,向两边移动。当剩下的最长可能palindrome substring都没当前
最长的palindrome subtring长的时候,立刻返回当前最长的解。
class Solution:
def longestPalindrome(self, s):
longest, mid = "", (len(s) - 1) / 2
i, j = mid, mid
while i >= 0 and j < len(s):
args = [(s, i, i), (s, i, i + 1), (s, j, j), (s, j, j + 1)]
for arg in args:
tmp = self.longestPali... 阅读全帖 |
|
w********m 发帖数: 1137 | 12 def q1(dictionary, target):
return [x for x in dictionary if sorted(x) == sorted(target)]
print q1(["hello","world","opt","pot"], 'pto')
def q2(input):
return sorted(input, key = lambda x: (x[0], x[2]))
print q2(['b-c','c-d','a-b','d-e']) |
|
d*k 发帖数: 207 | 13 好久没来贡献了,刚好有时间来,和大家交流一下。
这个题需要一个巧妙的思路,如果想不到是无法解答的。个人认为这种depend solely
on one key observation的题目不适合当面试题,而且以我的能力,除非有很好的提示
,不可能想出来。
设原来的结构为
a1a2a3...anb1b2b3...bn,需要变换为a1b1a2b2a3b3...anbn。可以把左右两个数组看
做A和B,长度分别为n。现在把A和B都划分成两个长度为n/2的数组,则输入可表示为
A1A2B1B2。这里的四个数组长度都是n/2(n是奇数也则A2和B2的长度比A1和B1的长度少
1)。有算法可以在O(n)时间内inplace地交换A2和B1得到A1B1A2B2。之后递归地处理
A1B1和A2B2。时间复杂度分析,上面的递归时间代价可以表示为
T(n) = O(n/2) + 2 * T(n / 2)
因此T(n) = O(nlogn)。
关于inplace地交换A2和B1的算法,相信大家都知道了。首先将A2B1这部分反序,设A2
长度为p,B1长度为q。反序后的部分,先将前q个元素反序,再将后面的p个... 阅读全帖 |
|
d*k 发帖数: 207 | 14 好久没来贡献了,刚好有时间来,和大家交流一下。
这个题需要一个巧妙的思路,如果想不到是无法解答的。个人认为这种depend solely
on one key observation的题目不适合当面试题,而且以我的能力,除非有很好的提示
,不可能想出来。
设原来的结构为
a1a2a3...anb1b2b3...bn,需要变换为a1b1a2b2a3b3...anbn。可以把左右两个数组看
做A和B,长度分别为n。现在把A和B都划分成两个长度为n/2的数组,则输入可表示为
A1A2B1B2。这里的四个数组长度都是n/2(n是奇数也则A2和B2的长度比A1和B1的长度少
1)。有算法可以在O(n)时间内inplace地交换A2和B1得到A1B1A2B2。之后递归地处理
A1B1和A2B2。时间复杂度分析,上面的递归时间代价可以表示为
T(n) = O(n/2) + 2 * T(n / 2)
因此T(n) = O(nlogn)。
关于inplace地交换A2和B1的算法,相信大家都知道了。首先将A2B1这部分反序,设A2
长度为p,B1长度为q。反序后的部分,先将前q个元素反序,再将后面的p个... 阅读全帖 |
|
p*****2 发帖数: 21240 | 15 val st: Stream[Int] = {
def ok(n: Int):Boolean = n match {
case 1 => true
case _ if n%2==0 => ok(n/2)
case _ if n%3==0 => ok(n/3)
case _ if n%5==0 => ok(n/5)
case _ => false
}
def loop(n: Int): Stream[Int] = if(ok(n)) n #:: loop(n+1) else loop(
n+1)
loop(1)
}
println(st.take(12).mkString(",")) |
|
p*****2 发帖数: 21240 | 16 object test extends App{
def depth(l: Any):Int = l match {
case n: Int => 1
case l: List[Any] => 1 + l.map(depth).max
}
def cal(l:Any, depth: Int):Int = l match {
case n: Int => n*depth
case l: List[Any] => l.map(cal(_, depth-1)).sum
}
val l = List(List(1,1), 2, List(1,1))
val res = cal(l, depth(l))
println(res)
} |
|
T****s 发帖数: 915 | 17 用python 实现,可是不知道问题出在哪里,结果显示output 和 input 一模一样。
请教大家。
谢谢。
~~~~~~~~~~~~~~~~~
class Solution:
# @param board, a 9x9 2D array
# Solve the Sudoku by modifying the input board in-place.
# Do not return any value.
class _State:
def __init__(self, board, row, col, rowsum, colsum, blocksum):
# board --- the board at the current state
# whichRow and whichCol --- row and col indices that need to
work
on (unfilled)
# rowStat, colStat and blockStat... 阅读全帖 |
|
p*****2 发帖数: 21240 | 18
想了一下,还是应该用actors
import akka.actor._
case class Foo(times: Int)
case class Bar(times: Int)
case object Foo
case object Bar
class FooActor(barActor: ActorRef) extends Actor {
def receive = {
case Foo(times) if times>0 =>
print(Foo)
barActor ! Bar(times)
}
}
class BarActor() extends Actor {
def receive = {
case Bar(times) =>
println(Bar)
sender ! Foo(times-1)
}
}
object test extends App{
val system = ActorSystem()
val barActor = system.actorOf(Props(new... 阅读全帖 |
|
L***s 发帖数: 1148 | 19 # non-idiomatic python code
# just to illustrate the algorithm clearer
def swap_chars(s, iBgn, iEnd):
""" Reverse chars in buffer s ranging from iBgn to iEnd (exclusive).
"""
for i in range(iBgn, (iBgn+iEnd)//2):
j = iBgn + iEnd - i - 1
s[i], s[j] = s[j], s[i]
def reverse_words_inplace(s):
""" Reverse all words in a sentence in-place.
E.g. 'this is simple' -> 'simple is this'
"""
n = len(s)
# First pass, char-level reversal in the sentence
... 阅读全帖 |
|
p*****2 发帖数: 21240 | 20 def split(arr:Array[Int], x: Int):Int = {
def loop(s: Int, c1: Int, e: Int, c2: Int): Int = {
if(s == e){
if(arr(s)==x && c1==c2+1 || arr(s)!=x && c1==c2+1) s-1
else if(arr(s)==x && c1+1==c2 || arr(s)!=x && c1==c2) s
else -1
}
else if(c1==c2) loop(s+1, c1+ (if(arr(s)==x) 1 else 0), e, c2)
else loop(s, c1, e-1, c2+ (if(arr(e)!=x) 1 else 0))
}
loop(0, 0, arr.length-1, 0)
} |
|
f**********t 发帖数: 1001 | 21 def nestSum(a, level):
res = 0
for x in a:
if isinstance(x, list):
res += nestSum(x, level + 1)
else:
res += int(x) * level
return res
def nestSumReverse(a):
res = 0
tmpSum = 0
level = 1
for x in a:
if isinstance(x, list):
curRes, curLevel = nestSumReverse(x)
res += curRes
level = max(curLevel + 1, level)
else:
tmpSum += int(x)
res += tmpSum * level
return r... 阅读全帖 |
|
f**********t 发帖数: 1001 | 22 def nestSum(a, level):
res = 0
for x in a:
if isinstance(x, list):
res += nestSum(x, level + 1)
else:
res += int(x) * level
return res
def nestSumReverse(a):
res = 0
tmpSum = 0
level = 1
for x in a:
if isinstance(x, list):
curRes, curLevel = nestSumReverse(x)
res += curRes
level = max(curLevel + 1, level)
else:
tmpSum += int(x)
res += tmpSum * level
return r... 阅读全帖 |
|
r*******t 发帖数: 99 | 23 贴个用1个lock,两个condition实现的。Code in Python:
def H():
# 加入一个H,检查是否可以形成H2O,若可以则notify另一个H和一个O
# 若不可则wait for cvH
global nH, nO, nH2O, lock, cvH, cvO
lock.acquire()
nH += 1
if nH >= 2 and nO >= 1:
nH -= 2
nO -= 1
nH2O += 1
print 'generating H2O molecule NO.%d' % nH2O
lock.release()
cvH.acquire()
cvH.notify()
cvH.release()
cvO.acquire()
cvO.notify()
cvO.release()
else:
lock.releas... 阅读全帖 |
|
H****S 发帖数: 1359 | 24 kinda remember someone talked about this in his blog. Here is the idea,
import java.util.concurrent._
import scala.collection.mutable
val hq = mutable.Buffer[Condition]
val oq = mutable.Buffer[Condition]
val lock = new ReentrantLock()
def h() {
lock.lock()
try {
if (hq.size >= 1 && oq.size >= 1) {
val ch = hq.last
ch.signal()
val co = oq.last
oh.signal()
hq.trimEnd(1)
oq.trimEnd(1)
println("h")
} else {
val ch = lock.newCond... 阅读全帖 |
|
t********5 发帖数: 522 | 25 def reverseIt(input):
return input[::-1]
def reverseItAdvanced(input):
return ' '.join(input.split()[::-1])
(troll) |
|
d****n 发帖数: 397 | 26 DP
python solution
class Solution:
"""
@param A: A positive integer which has N digits, A is a string.
@param k: Remove k digits.
@return: A string
"""
def DeleteDigits(self, A, k):
# write you code here
l = len(A)
S = [['' for j in range(k + 1)] for i in range(l + 1)]
T = ''
for j in range(0, k + 1):
S[j][j] = ''
for i in range(1, l + 1):
T += A[i - 1]
S[i][0] = T
for j in range(1... 阅读全帖 |
|
d****n 发帖数: 397 | 27 DP
python solution
class Solution:
"""
@param A: A positive integer which has N digits, A is a string.
@param k: Remove k digits.
@return: A string
"""
def DeleteDigits(self, A, k):
# write you code here
l = len(A)
S = [['' for j in range(k + 1)] for i in range(l + 1)]
T = ''
for j in range(0, k + 1):
S[j][j] = ''
for i in range(1, l + 1):
T += A[i - 1]
S[i][0] = T
for j in range(1... 阅读全帖 |
|
r*****n 发帖数: 35 | 28 case class TreeNode(value: Char, var left: Option[TreeNode] = None, var
right: Option[TreeNode] = None)
object TreeBuilder {
//recursive version
def recursive(input: String, start: Int): (Int, Option[TreeNode]) ={
if (start >= input.length) {
(start, None)
} else {
val cur = Some(TreeNode(input(start)))
if (start == input.length - 1) {
(start + 1, cur)
} else {
input(start + 1) match {
case '?' =>
val (loffset, l) = recursiv... 阅读全帖 |
|
C****t 发帖数: 53 | 29 A python version:
def num(maps, s): ######## transform string to 4-based number
digit = 0
for i in range(len(s)):
digit = 4*digit + maps[s[i]]
return digit
def findRepeat(s):
maps = {'A':0, 'C':1,'G':2,'T':3}
bitmap = [0]*pow(4,2)
for i in range(len(s) - 2+1):
bitmap[ num[maps, s[i:i+2] ] += 1
invmaps = {v:k for k,v in maps.items()} ####### reverse maps
for i in range(len(bitmap)):
if bitmap[i] > 1:
print (invmaps[i//4] + in... 阅读全帖 |
|
C****t 发帖数: 53 | 30 A python version:
def num(maps, s): ######## transform string to 4-based number
digit = 0
for i in range(len(s)):
digit = 4*digit + maps[s[i]]
return digit
def findRepeat(s):
maps = {'A':0, 'C':1,'G':2,'T':3}
bitmap = [0]*pow(4,2)
for i in range(len(s) - 2+1):
bitmap[ num[maps, s[i:i+2] ] += 1
invmaps = {v:k for k,v in maps.items()} ####### reverse maps
for i in range(len(bitmap)):
if bitmap[i] > 1:
print (invmaps[i//4] + in... 阅读全帖 |
|
x*******9 发帖数: 138 | 31 nested_list = [[1,2], 1, [2, [2,1]]]
def revSum(nlist):
(depth, res) = dfs(nlist)
return res
def dfs(nlist):
nlist_sum = 0
s = 0
max_lv = 1
for item in nlist:
if isinstance(item, list):
(depth, res) = dfs(item)
nlist_sum += res
max_lv = max(max_lv, depth + 1)
else:
s += item
nlist_sum += s * max_lv
return (max_lv, nlist_sum)
print revSum(nested_list)
(已加入肯德基豪华午餐 |
|
x*******9 发帖数: 138 | 32 nested_list = [[1,2], 1, [2, [2,1]]]
def revSum(nlist):
(depth, res) = dfs(nlist)
return res
def dfs(nlist):
nlist_sum = 0
s = 0
max_lv = 1
for item in nlist:
if isinstance(item, list):
(depth, res) = dfs(item)
nlist_sum += res
max_lv = max(max_lv, depth + 1)
else:
s += item
nlist_sum += s * max_lv
return (max_lv, nlist_sum)
print revSum(nested_list)
(已加入肯德基豪华午餐 |
|
c******h 发帖数: 46 | 33 就是说 {1,2} 的weight 是1了对吧 因为nlist_sum没有乘max_lv
我觉得是对的
2L说{1,2} weight是2不知道为啥
nested_list = [[1,2], 1, [2, [2,1]]]
def revSum(nlist):
(depth, res) = dfs(nlist)
return res
def dfs(nlist):
nlist_sum = 0
s = 0
max_lv = 1
for item in nlist:
if isinstance(item, list):
(depth, res) = dfs(item)
nlist_sum += res
max_lv = max(max_lv, depth + 1)
else:
s += item
nlist_sum += s * max_lv
return (max_lv, nlist_sum)
p... 阅读全帖 |
|
C****t 发帖数: 53 | 34 来自主题: JobHunting版 - 问个面试题 # each cube is an array which contains three pairs of colors of opposite
faces
class Solution:
def isTower(self, cubes):
color = self.checkColor(cubes[0])
if color == 'bad': return False
for i in range(1, len(cubes)):
icolor = self.checkColor(cubes[i])
if icolor == 'bad' or icolor != color:
return False
return True
def checkColor(self,cube):
f1, f2, f3 = cube
c1 = ['bad', f1[0]] [f1[0] == f1[1]]
... 阅读全帖 |
|
C****t 发帖数: 53 | 35 来自主题: JobHunting版 - 问个面试题 # each cube is an array which contains three pairs of colors of opposite
faces
class Solution:
def isTower(self, cubes):
color = self.checkColor(cubes[0])
if color == 'bad': return False
for i in range(1, len(cubes)):
icolor = self.checkColor(cubes[i])
if icolor == 'bad' or icolor != color:
return False
return True
def checkColor(self,cube):
f1, f2, f3 = cube
c1 = ['bad', f1[0]] [f1[0] == f1[1]]
... 阅读全帖 |
|
C****t 发帖数: 53 | 36 Q1.
def swap(nums):
n = len(nums)
for i in range(n):
tmp = origIdx(i, n//2)
while tmp < i: tmp = origIdx(tmp, n//2)
nums[i], nums[tmp] = nums[tmp], nums[i]
print(nums)
def origIdx(cur, n):
return (cur%2)*n + cur//2 |
|
d******e 发帖数: 2265 | 37 2n worst time
def swapandlabel(l, r, i, j):
''' swap array and label ratation.'''
tmp = l[i]
l[i] = l[j]
l[j] = tmp
r[i] = r[j]
r[j] = j
def shuffle(l, r):
for i in range(len(r)):
while r[i] != i:
swapandlabel(l, r, i, r[index]) |
|
C****t 发帖数: 53 | 38 def OneorZero(a, b):
return recur(a, b) <=1
def recur(a,b):
# ---------base cases
if not a.hasNext() and not b.hasNext(): return 0
elif not b.hasNext():
a.next()
if a.hashNext(): return 2
else: return 1
else:
b.next()
if b.hashNext(): return 2
else: return 1
cp_a, cp_b = a, b
if a.next() == b.next(): return 0 + recur(a,b)
else: return 1 + min( recur(a,b), recur(cp_a, b), recur(a, cp_b) ) |
|
S*******C 发帖数: 822 | 39 Amazon面试题, leetcode变种
string 有标点符号,我不希望标点符号被倒过来, 例如 “abc, def” ,结果是“
cba, def”,给的标点符号包括 “, 。 ! ?” |
|
|
x**********4 发帖数: 70 | 41 import re
class Solution:
def evaluate(self, expr):
tokens = re.split('[ ()]', expr)
tokens = [token for token in tokens if token]
var, stack, i = {}, [], 0
keywords = set(['add', 'mult', 'let'])
while i < len(tokens):
if tokens[i] == 'add' or tokens[i] == 'mult':
stack.append(tokens[i])
i += 1
elif tokens[i] == 'let':
i += 1
while i < len(tokens) and tokens[i] not ... 阅读全帖 |
|
A*******e 发帖数: 2419 | 42 不可能吧。这个python版都要20行了。
2/3/4-sum实际每个都有三个版本:
判断有没有解,只需找一组。
找所有唯一解
找所有解。
看了一下,我的版本比较长,是因为找所有解,LC只需要所有唯一解,这样可简化一些。
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
num.sort()
result = []
for i in range(len(num)):
twoSumTuples = self.twoSum(num[i+1:], 0 - num[i])
if twoSumTuples:
for pair in twoSumTuples:
threeSum = [num[i]] + pair
if threeS... 阅读全帖 |
|
d****n 发帖数: 397 | 43 听你的意思应该是从52张牌里面随机选一张1/52.然后随机放回1/2概率牌数不变,1/2
牌数少一。
其实就是52 * 2
下面是code
#! /usr/bin/python
import random
class Solution:
def card(self,n):
steps = 0
while n != 0:
if random.random() < 0.5:
n -= 1
steps += 1
return steps
def run_card_avg(self):
M = 1000
n = 52
sum = 0
for i in range(M):
# print i, self.card(n)
sum += self.card(n)
return sum * 1.0 / M
if __name__ == "__main__":
sol = Solution()
print sol.run_ca... 阅读全帖 |
|
g******n 发帖数: 10 | 44 Sample Input
1 2 3
2 1 3
3 2 1 5 4 6
1 3 4 2
3 4 5 1 2
Sample Output
YES
YES
YES
NO
NO
--------------------------------------
Python 版:
import sys
def check(nodes):
return helper(nodes, 0, len(nodes), -sys.maxsize-1, sys.maxsize)
def helper(nodes, start, end, min_value, max_value):
if start >= end:
return True
root = nodes[start]
if not (min_value < root < max_value):
return False
i = start + 1
while i < end and node... 阅读全帖 |
|
t*8 发帖数: 14 | 45 收到的消息的结构如下
# Message examples:
#
# (business_name, ip, timestamp)
# (“sammy’s”, 82.13.31.123, 1402341603)
# (“sammy’s”, 82.14.34.125, 1402341513)
# (“osha thai”, 92.13.14.12, 1402341523)
每5秒钟收到新消息,调用process_message。要实现一个函数business_name返回10分
钟内出现次数最多的business_name。
# refresh time: 5 seconds
# window: 10 minutes
#
# def process_message(message):
# pass
#
# def business_name():
# pass |
|
d****n 发帖数: 397 | 46 贴一个python 代码。 这个有点像quick sort里面的deterministic nlgn 算法。重点
是将rank r按两个数组长度分配。
然后在舍弃两个数组其中一个的左边一段。
class Solution:
# @return a float
def findMedianSortedArrays(self, A, B):
m = len(A)
n = len(B)
i = 0
j = m - 1
s = 0
t = n - 1
if (m + n) % 2 == 0:
r1 = (m + n) / 2
r2 = r1 + 1
median = (self.findRankr(A, B, i, j, s, t, r1) + self.findRankr(
A, B, i, j, s, t, r2)) / 2.0
else:
r1 = (... 阅读全帖 |
|
F*****o 发帖数: 32 | 47 class TreeNode:
def __init__(self,x):
self.child=[]
self.val=x
class Solution:
def strToTree(self,s):
if len(s)==0: return None
stack=[]
for i in range(len(s)):
if s[i]=='(': stack.append(s[i])
elif s[i].isalpha():
stack.append(TreeNode(s[i])) #push to stack except ')'
else:
t,temp=stack.pop(),[]
while t!='(':
temp.append(t)
t... 阅读全帖 |
|
r****t 发帖数: 10904 | 48 可能是无递归的最简解法,因为 python int 不限大小,可随便上至 octillion,
whatever
import locale
eng = { '0': '', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
'5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10':
'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'forteen',
'15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen',
'19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty',
'50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty','90': 'nighty'
, ... 阅读全帖 |
|
b******b 发帖数: 713 | 49 面了google/facebook/linkedin/two sigma/aqr/uber, 被uber/aqr据了。基本所有面
过的题:
hedge fund 1:
1. Write a function that takes as input integers P and Q and returns P to
the power of Q. Note any assumptions you make and the complexity of the
algorithm. We expect you to do better than O(Q).
2. Write a function that takes as input an array of 1 million integers,
such that 1 ≤ x ≤ 10 for every element x in the array, and returns the
sorted array. The sort does not need to occur in-place. Obviously you ... 阅读全帖 |
|
m******3 发帖数: 346 | 50 多谢楼主
下面这几道题怎么做啊
tech company 2:
1. have N offices globally. each office have a local calender with holidays.
you are allowed to move every weekend to different office, how to get max
numbers of holidays. follow up, if for each office, there are only certain
set of offices are reacheable, e.g. if you are in NYC this weekend, you can
move to SF, or London. If you are in SF, you can move to NYC and Beijing,
etc. how to max the holidays.
2. Binary tree find the longest consecutive path.
[能详细说说题意么?]
... 阅读全帖 |
|