I collected a bunches of leetcode code solutions and now put them in one post. This post contains the following questions:
* BST Iterator
* Factorial Trailing Zeros
* Excel number
* Decimal
* Find Peak Element
* Min stack
* Majority elements
* Trailing zeros
* Tree Travel
Also, after realing leetcode online judge have numerous bug in python test case, I decided to turn to C++. So, here comes the solutions.
BST Iterator
Question:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Basic logic:
The smallest value is will be on the left-most node, therefore the first thing to do is to dive to the deepest ad left-most of the tree. Next we can return the value of the middle node, then its left node. A list of nodes on path should be maintain to avoid return repeated value.
classBSTIterator:# @param root, a binary search tree's root nodedef__init__(self,root):# ancestors of current node, self.ancestors=[]# current node, initialized by rootself.current=None# current point to the smallest valueself.current=rootself.dive()# @return a boolean, whether we have a next smallest numberdefhasNext(self):returnself.current!=NonedefhasLeft(self):returnself.hasNext()defhasRight(self):returnself.hasNext()# @return an integer, the next smallest numberdefnext(self):# every time we dive first,# so the smallest value is the current noderval=self.current.valifnotself.hasRight():# if no right nodes# the next smallest value will be current node's parentiflen(self.ancestors)==0:self.current=Noneelse:self.current=self.ancestors.pop()else:# if there is right node, it's value will smaller than parent's, # so step into it, then dive to left-mostself.current=self.current.rightself.dive()returnrvaldefdive(self):whileself.hasLeft():self.ancestors.append(self.current)self.current=self.current.left
Excel column number
Qusetion
Given Excel column number, return the corresponding digit number
Basic logic
A conversion of number systems( thought not a typical one) . First we map characters to numbers, them multiply digit in the Nth location with 26^n, sum and get the result.
123456789101112131415
classSolution:# @param s, a string# @return an integerdef__init__(self):self.map='ABCDEFGHIJKLMNOPQRSTUVWXYZ'deftitleToNumber(self,s):rval=0foriinxrange(len(s)):# need to revese the stringrval+=self.char2Int(s[len(s)-i-1])*(26**i)returnrvaldefchar2Int(self,char):returnself.map.index(char)+1
Majority element
Question:
Given an array of size n, find the majority element. The majority element is the element that appears more than n/2 times.
Basic logic:
Use a counter(map) to calculate how many times each elements has occured and return if times > length/2.
12345678910111213
classSolution:# @param num, a list of integers# @return an integerdefmajorityElement(self,num):map={}length=float(len(num))forninnum:try:map[n]+=1except:map[n]=1ifmap[n]>=length/2:returnn
Trailing zeros.
Question:
Given an integer n, return the number of trailing zeroes in n!.
Basic logics:
This is more a math problem than a code problem. Notice that 1 x 2 x 3 ... x 5 ... x 10 ... with every 5( or n x 5 ) there must be a 2(ornx2). And the trailing zeros must be the result of (2x5)^n. Therefore, the problem becomes ‘How many 5 are there in it’s factors’. ( Need to rewrite this paragraph )
123456789
classSolution:# @return an integerdeftrailingZeroes(self,n):num=0k=1while5**k<=n:num+=int(n/(5**k))k+=1returnnum
Find peak elements
Questions
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
Basic logic
Easy problem, just iter over and compare each element with its neighbours. If the num[i] can equals num[i+], we first deduplicate, and then compare. Need some attentions on the conner case( length = 0,1 or the peak occurs on the head or tails)
classSolution:# @param num, a list of integer# @return an integerdeffindMin(self,num):iflen(num)==1:returnnum[0]eliflen(num)==2:returnmin(num[0],num[1])else:# deduplicatewhilelen(num)>1andnum[0]==num[-1]:num.pop()foriinxrange(len(num)):try:ifnum[i]==num[i+1]:num.pop(i)except:breakreturnself.findMinNoRepeat(num)deffindMinNoRepeat(self,num):iflen(num)==1:returnnum[0]eliflen(num)==2:returnmin(num[0],num[1])else:buf=[]index=0length=len(num)foriinxrange(3):buf.append(num[index])index+=1index-=1whileTrue:ifself.isMax(buf):returnbuf[1]else:index+=1index%=lengthifnum[index]!=buf[-1]:buf.pop(0)buf.append(num[index])defisMax(self,buf):returnbuf[1]<buf[0]andbuf[2]>buf[1]
Min Stack
question
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
* push(x) -- Push element x onto stack.
* pop() -- Removes the element on top of the stack.
* top() -- Get the top element.
* getMin() -- Retrieve the minimum element in the stack.
Basic logic
The key is to maintain double stack: one for normal push() and pop(), the other for the operation getMin(). When a new min value is pushed, we also push it to the min_stack, when it pops, we also pop it from min_stack. So the minimum value is always on the top of min_stack.
12345678910111213141516171819202122232425
classMinStack:def__init__(self,node=None):self.stack=[]self.minStack=[]# @param x, an integer# @return an integerdefpush(self,x):self.stack.append(x)ifself.minStack==[]orx<=self.minStack[-1]:self.minStack.append(x)# @return nothingdefpop(self):val=self.stack.pop()ifval==self.minStack[-1]:self.minStack.pop()# @return an integerdeftop(self):returnself.stack[-1]# @return an integerdefgetMin(self):returnself.minStack[-1]
Fraction to Recurring Decimal
Question
Basic logics.
Easy job, just a little bit tedious. By implementing a long divide, we can easily find the answer. Remember to store every ( quotient,remainder )pairs so that we can know when it starts repeat itself. The python test case is wrong. See this post. After this solution, I turned to C++, which should have better judge system.
classSolution():def__init__(self):pass# @return a stringdeffractionToDecimal(self,numerator,denominator):# corner caseifnumerator==0:return'0'# if no decimal numberifnumerator%denominator==0:returnstr(numerator/denominator)else:# reduction of a fraction, not necessaryfraction=2whileTrue:whilefraction<=min(abs(numerator),abs(denominator)):ifnumerator%fraction==0anddenominator%fraction==0:numerator/=fractiondenominator/=fractionbreakfraction+=1# if it's end, end it. else ,restart againiffraction>=min(abs(numerator),abs(denominator)):breakfraction=2# Decomposition quality factor to find if demimal repeated itself, not necessary.denom=abs(denominator)whiledenom%2==0:denom/=2whiledenom%5==0:denom/=5repeated=denom!=1result_list=[]# get the symbol of final resultifnumerator*denominator<0:result_list+=[('-','-')]numerator=abs(numerator)denominator=abs(denominator)# start long divide loop( core algo )add_dot=Trueindex=0whileTrue:# long dividequotient=numerator/denominatorremainder=numerator%denominatornumerator=remainder# check if repreated, if not, ready for the next divisionif(remainder,quotient)inresult_list:repreat_start_locaation=result_list.index((remainder,quotient))result_list.insert(repreat_start_locaation,('(','('))result_list.append((')',')'))break# append this result of divisionresult_list.append((remainder,quotient))# if remainder is 0, it's not a repreated number ifremainder==0:breakifadd_dot:result_list.append(('.','.'))add_dot=Falsenumerator*=10index+=1ifindex>100:break# construck resultresult_list.reverse()result_str=''whilelen(result_list)>0:remainder,quotient=result_list.pop()result_str+=str(quotient)returnresult_str