Posts

Showing posts from July, 2020

Counter in python

Counter class is a special type of object data-set provided with the collections module in Python3. It collects how many elements it have in a string or a dictionary or a list. from collections import Counter S = "aab" a = Counter(S) method of Counter: elements() for i in a.elements():          print(i) we get aab(return to all the elements) get('a') most_common(1) keys() values() update('aabb') add the elements in the counter subtrct('aa') make the subtract with the original counter

Some Tips to improve Efficiency in Python

if n % 2  can change to  if n & 1  if n //= 2 can change to  if n >> 1 one line to do if condition [on_true] if [expression] else [on_false] 

leetcode write up for 91-120 problems

100 .  Same Tree  base case 都为空返回true。然后用迭代来做。 class Solution(object):     def isSameTree(self, p, q):         return (not p and not q) or (p and q and p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)) 101 .  Symmetric Tree 递归的方法,不然会写的很繁琐。有点难。 class Solution:     def isSymmetric(self, root):                  if root==None:             return(True)         p1 = root.left         p2 = root.right         return(self.traverse(p1,p2))     def traverse(self,p1,p2):         if p1==None and p2==None:        ...

leetcode write up for 61-90 problems

61 .  Rotate List 要考虑的特殊case比较多,listnode是share的,修改也会互相改变,但是head不同,所以我们要知道先改哪些。 class Solution(object):     def rotateRight(self, head, k):         if not head:             return None         if not head.next:             return head         pointer = head         count = 1         while pointer.next:# calculate the lenth of the total listNode             pointer = pointer.next             count+=1         rotateTimes = k % count #calculate the steps it have to ratate    ...

leetcode write up for 31-60 problems

31 .  Next Permutation 从后往前,后一个数大于前一个数的时候就说明找到了要修改的位置,  但是不能直接置换这两个,要取后面的最小的来置换。 由于后面一个个比较过来的,所以是从大到小排序的。 所以再来一个for循环找到刚好比 i-1 这个数大一点的来置换这个数。 然后最后关键一步,要把后面的从小到大的排序(reverse)。 nums[i:][::-1] 是将i到后面的都反序。 class Solution(object):     def nextPermutation(self, nums):         i = len(nums)-1         while i > 0:             if nums[i] > nums[i-1]:                 for j in xrange(len(nums)-1, 0, -1):                     if nums[j] > nums[i-1]:                         nums[j], nums[i-1] = nums[i-1], nums[j]   ...