leetcode刷题笔记-math

780. Reaching Points

leetcode刷题笔记-math_第1张图片

First while:  x, y comes fromx, k*x+y or x+k*y, y  for each step

Second: check if we reduce target points to (x, y+kx) or (x+ky, y)

class Solution(object):
    def reachingPoints(self, sx, sy, tx, ty):
        while sx < tx and sy < ty:
            tx, ty = tx % ty, ty % tx
         
        return sx == tx and sy < ty and (ty - sy) % sx == 0 or \
               sy == ty and sx < tx and (tx - sx) % sy == 0

自己写的TLE的方法:

        level = [(sx, sy)]
        while True:
            Next = []
            xmin = float('inf')
            ymin = float('inf')
            while level:
                x, y = level.pop(0)
                if (x, y) == (tx, ty):
                    return True
                Next.append((x, x+y))
                Next.append((x+y, y))
                xmin = min(xmin, x+y)
                ymin = min(ymin, y+x)
            if xmin > tx and ymin > ty: return False
            level = Next

 

238. Product of Array Except Self

leetcode刷题笔记-math_第2张图片

class Solution(object):
    def productExceptSelf(self, nums):
        # The output array does not count as extra space for the purpose of space complexity analysis.
        # 所以res 不算extra space 所以O(1) space
        # 先从左到右乘,before的结果是 nums[0]*..*nums[i-1]不包括Nums[i]
        # 再从右到左乘,after的结果是nums[i+1]到nums[n-1]的乘积
        # 前后相乘就是结果
        res = []
        before = 1
        for i in xrange(len(nums)):
            res.append(before)
            before *= nums[i]
        after = 1
        for i in xrange(len(nums)-1, -1, -1):
            res[i] *= after
            after *= nums[i]
        return res

 

89. Gray Code

leetcode刷题笔记-math_第3张图片

leetcode刷题笔记-math_第4张图片

class Solution(object):
    def grayCode(self, n):
        res = [0]
        for i in xrange(n):
            add = pow(2, i)
            for n in reversed(res):
                res.append(n+add)
        return res

 

311. Sparse Matrix Multiplication

leetcode刷题笔记-math_第5张图片

class Solution(object):
    def multiply(self, A, B):
        # 无hash table的做法,有的也类似
        if not A or not B: return 
        rowA = len(A)
        colA = len(A[0])  # rowB
        colB = len(B[0])
        
        re = [[0]*colB for _ in xrange(rowA)]
        for i, row in enumerate(A):
            for k, eleA in enumerate(row):
                if eleA:
                    for j, eleB in enumerate(B[k]):  # K
                        if eleB:
                            re[i][j] += eleA * eleB  # A[i][k] * B[k][j]
        return re

296. Best Meeting Point

leetcode刷题笔记-math_第6张图片

这题知道要找median的话就是easy level的题目

class Solution(object):
    def minTotalDistance(self, grid):
        """
        Manhattan Distance, find the median
        """
        rowIdx = [i for i in xrange(len(grid)) for j in xrange(len(grid[0])) if grid[i][j]]
        colIdx = [j for i in xrange(len(grid)) for j in xrange(len(grid[0])) if grid[i][j]]
        colIdx.sort()
        row = rowIdx[len(rowIdx) / 2]
        col = colIdx[len(rowIdx) / 2]
        return sum(abs(i-row)+abs(j-col) for i in xrange(len(grid)) for j in xrange(len(grid[0])) if grid[i][j])

227. Basic Calculator II

leetcode刷题笔记-math_第7张图片

class Solution(object):
    def calculate(self, s):
        s += '+'
        stack, num, preOp = [], 0, '+'
        for c in s:
            if c.isdigit():
                num = num*10 + int(c)
            elif not c.isspace():
                if preOp == '-': stack.append(-num)
                elif preOp == '+': stack.append(num)
                elif preOp == '*':
                    stack.append(stack.pop() * num)
                elif preOp == '/':
                    n = stack.pop()  # stack.append(int(stack.pop() / num)) 不行,因为14-3/2中-3/2 = -2
                    # *(n/abs(n))如果是负数的话相当于乘以-1 变成正数的除法
                    stack.append(0 if n == 0 else n * (n/abs(n)) / num * (n/abs(n)))  
                preOp, num = c, 0
        return sum(stack)

 

224. Basic Calculator

leetcode刷题笔记-math_第8张图片

class Solution(object):
    def calculate(self, s):
       
        res, num, sign, stack = 0, 0, 1, []
        for c in s:
            if c.isdigit():
                num = num*10 + int(c)
            elif c in ['+', '-']:
                res += num * sign  # 加上前面的num
                num = 0                
                sign = [-1, 1][c == '+']
            elif c == '(':
                stack.append(res)
                stack.append(sign)
                res, num, sign = 0, 0, 1  # num其实在 +, -的时候就set为0了
            elif c == ')':
                res += num*sign
                sign = stack.pop()
                res = stack.pop() + sign*res
                num = 0
                
        return res + num*sign  # 最后一个循环里面加不到

204. Count Primes

leetcode刷题笔记-math_第9张图片

如果2是prime 则x=2*j 的数都不是prime。   2*j < n-1 则 j < (n-1) / 2

class Solution(object):
    def countPrimes(self, n):
        if n <= 2:
            return 0

        primes = [True] * n
        primes[0] = primes[1] = False
        for i in xrange(2, n):
            if primes[i] == True:
                for j in xrange(2, (n-1)/i + 1):
                    primes[i*j] = False
        return sum(primes)

 

462. Minimum Moves to Equal Array Elements II

leetcode刷题笔记-math_第10张图片

这题只要记住The Median Minimizes the Sum of Absolute Deviations (The L1L1 Norm)

Suppose we have a set SS of real numbers. Show that

∑s∈S|s−x|∑s∈S|s−x|

is minimal if xx is equal to the median

证明:https://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations-the-l-1-norm

781. Rabbits in Forest

leetcode刷题笔记-math_第11张图片

第一次解法,通过,但是写法感觉略复杂,虽然时间复杂度是O(n)

class Solution(object):
    def numRabbits(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        if not answers:
            return 0
        res = 0
        answers = sorted(answers)
        rest = 0
        for i in xrange(len(answers)):
            if i == 0:
                res += answers[i] + 1
                rest = answers[i]
            else:
                if answers[i] == 0:
                    res += 1
                elif answers[i] != answers[i-1]:
                    res += answers[i] + 1
                    rest = answers[i]
                elif answers[i] == answers[i-1] and rest > 0:
                    rest -= 1
                elif answers[i] == answers[i-1] and rest == 0:
                    res += answers[i] + 1
                    rest = answers[i]
                
        return res

参考了讨论里面的答案:写法很优雅速度更慢

leetcode刷题笔记-math_第12张图片

class Solution(object):
    def numRabbits(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        c = collections.Counter(answers)
        return sum((c[i]+i) / (i+1) * (i+1) for i in c)

319. Bulb Switcher

leetcode刷题笔记-math_第13张图片

思路:

leetcode刷题笔记-math_第14张图片

class Solution(object):
    def bulbSwitch(self, n):
        return int(math.sqrt(n))

41. First Missing Positive

做的第一题Hard题,主要难点在O(n)和O(c)space。

leetcode刷题笔记-math_第15张图片

思路:不得不说太棒了!

leetcode刷题笔记-math_第16张图片

class Solution(object):
    def firstMissingPositive(self, nums):
        nums.append(0)  # because the missing positive interger will be in the range from [1, n+1]
        n = len(nums)
        for i in xrange(n):  # [7, 8, 9, 0] => [0, 0, 0, 0]
            if nums[i] < 0 or nums[i] >= n:  
                nums[i] = 0
        
        for i in xrange(n):  # use the index to store the frequence of the num
            nums[nums[i]%n] += n  # 这里要取余,因为之前可能被加了n

        for i in xrange(1, n):
            if nums[i] / n == 0:
                return i
        return n

 

396. Rotate Function 

leetcode刷题笔记-math_第17张图片

思路:

leetcode刷题笔记-math_第18张图片

F(k) = F(k-1) + Sum - nA(-k) 

class Solution(object):
    def maxRotateFunction(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        if not A:
            return 0
        
        Sum = sum(A)
        n = len(A)
        F = [0] * n
        for i in xrange(n):
            if i == 0:
                F[i] = sum(e*i for i, e in enumerate(A))
            else:
                F[i] = F[i-1] + Sum - n*A[-i]
                
        return max(F) 

313. Super Ugly Number

class Solution(object):
    def nthSuperUglyNumber(self, n, primes):
        """
        :type n: int
        :type primes: List[int]
        :rtype: int
        """
        uglys = [1]
        points = [0] * len(primes)
        for i in xrange(n - 1):
            Min = 2**32
            for j in xrange(len(primes)):
                Min = min(Min, uglys[points[j]] * primes[j])

            for jj in xrange(len(primes)):
                if uglys[points[jj]] * primes[jj] == Min:
                    points[jj] += 1
     
            uglys.append(Min)
 
        return uglys[-1]

leetcode刷题笔记-math_第19张图片

leetcode刷题笔记-math_第20张图片

334. Increasing Triplet Subsequence 

leetcode刷题笔记-math_第21张图片

这么简单粗暴的方法为啥我一开始没想出来?

class Solution(object):
    def increasingTriplet(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        c1, c2 = 2**31, 2**31
        for n in nums:
            if n <= c1:
                c1 = n
            elif n <= c2:
                c2 = n
            else:
                return True
        return False

50. Pow(x, n)

leetcode刷题笔记-math_第22张图片

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n < 0:
            return 1 / self.myPow(x, -n)
        
        if n == 0:
            return 1
        elif n == 2:
            return x*x
        
        if n % 2 == 0:
            return self.myPow(self.myPow(x, n/2), 2)
        else:
            return x * self.myPow(self.myPow(x, n/2), 2)

43. Multiply Strings

leetcode刷题笔记-math_第23张图片

Multiplication

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        n1, n2 = len(num1), len(num2)
        indices = [0] * ((n1-1) + (n2-1) + 1 + 1)
        
        for j in xrange(n2):
            for i in xrange(n1):
                num = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))
                indices[i+j] += num / 10
                indices[i+j+1] += num % 10
        
        for i in xrange(len(indices)-1, 0, -1):
            indices[i-1] += indices[i] / 10
            indices[i] = str(indices[i] % 10)
        indices[0] = str(indices[0])
        
        p = 0
        for i in xrange(len(indices)-1):
            if indices[i] == '0':
                p += 1
            else:
                break
        return "".join(indices[p:])

29. Divide Two Integers

leetcode刷题笔记-math_第24张图片

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        sign = 1
        if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0):
            sign = -1
        dividend, divisor = abs(dividend), abs(divisor)
        
        if divisor == 0:
            return sys.maxsize
        
        if dividend == 0 or divisor > dividend:
            return 0
        
        res = self._divide(dividend, divisor)
        if res > 2**31-1:
            return 2**31-1 if sign == 1 else -2**31
        
        return res*sign
        
    
    def _divide(self, dividend, divisor):
        
        if dividend < divisor:
            return 0
        _sum = divisor
        mutiple = 1
        
        while (_sum + _sum) < dividend:
            _sum += _sum  # 两倍两倍的加可以提高运行速度
            mutiple += mutiple
            
        return mutiple + self._divide(dividend-_sum, divisor)
        

247. Strobogrammatic Number II

leetcode刷题笔记-math_第25张图片

leetcode刷题笔记-math_第26张图片

class Solution(object):
    def findStrobogrammatic(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        oddMiddleCandicate = ['0', '1', '8']
        evenMiddleCandicate = ["11","69","88","96", '00']
        
        if n == 1:
            return oddMiddleCandicate
        
        if n == 2:
            return evenMiddleCandicate[:-1]
        
        if n % 2:
            pre, middle = self.findStrobogrammatic(n-1), oddMiddleCandicate
        else:
            pre, middle = self.findStrobogrammatic(n-2), evenMiddleCandicate
        
        mid_idx = (n-1) / 2
        return [x[:mid_idx] + y + x[mid_idx:] for x in pre for y in middle]

 

248. Strobogramm Number III

leetcode刷题笔记-math_第27张图片

class Solution(object):
    def strobogrammaticInRange(self, low, high):
        """
        the low and high numbers are represented as string.
        """
        maps = aps={"0":"0","1":"1","6":"9","8":"8","9":"6"}
        cl, ch = len(low), len(high)  # character length low and high
        if cl > ch or (cl == ch and low > high): return 0
        
        ans = ['', '0', '1', '8']
        count = 0
        
        while ans:
            temp = []
            
            for s in ans:  
                if ch - len(s) >= 2:
                    for key in maps:
                        temp.append(key+s+maps[key])
                
                if cl <= len(s) <= ch:  # 过滤掉不满足的,把满足的结果 count+1
                    if len(s) == cl and s < low: continue
                    if len(s) == ch and s > high: continue
                    if len(s) > 1 and s[0] == '0': continue  # leading zero
                    count += 1
                    
            ans = temp
            
        return count

 

65. Valid Number

leetcode刷题笔记-math_第28张图片

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        #define a DFA
        state = [{}, 
              {'blank': 1, 'sign': 2, 'digit':3, '.':4}, 
              {'digit':3, '.':4},
              {'digit':3, '.':5, 'e':6, 'blank':9},
              {'digit':5},
              {'digit':5, 'e':6, 'blank':9},
              {'sign':7, 'digit':8},
              {'digit':8},
              {'digit':8, 'blank':9},
              {'blank':9}]
        currentState = 1
        for c in s:
            if c >= '0' and c <= '9':
                c = 'digit'
            if c == ' ':
                c = 'blank'
            if c in ['+', '-']:
                c = 'sign'
            if c not in state[currentState].keys():
                return False
            currentState = state[currentState][c]
        if currentState not in [3,5,8,9]:
              return False
        return True

 

你可能感兴趣的:(Algorithm)