leetcode一些基础题
1. String to Integer(atoi) https://oj.leetcode.com/problems/string-to-integer-atoi/
这道题不难,有许多细节需要注意。
(1)空白符
(2)最大值和最小值
(3)非数字
1 def atoi(self, str): 2 lenStr = len(str) 3 num = 0 4 INT_MAX = 2147483647 5 INT_MIN = -2147483648 6 sign = 1 7 if lenStr == 0: 8 return 0 9 s = 0 10 while str[s] == ' ': 11 s += 1 12 if str[s] == '-': 13 sign = -1 14 s += 1 15 elif str[s] == '+': 16 s += 1 17 while s < lenStr and str[s].isdigit(): 18 num = num*10 + int(str[s]) 19 s += 1 20 num = num*sign 21 if num > INT_MAX: 22 return INT_MAX 23 elif num < INT_MIN: 24 return INT_MIN 25 else: 26 return num
2. Implement strStr()(https://oj.leetcode.com/problems/implement-strstr/)
解法一: 暴力,时间复杂度O(m*n)
解法二:利用KMP算法。 KMP是前缀匹配算法,时间复杂度为O(m+n).
1 def KMP(self, needle): 2 k = 0 3 pi = [0 for i in range(len(needle))] 4 for p in range(1, len(needle)): 5 while k > 0 and needle[k] != needle[p]: 6 k = pi[k-1] 7 if needle[k] == needle[p]: 8 k += 1 9 pi[p] = k 10 return pi 11 12 def strStr(self, haystack, needle): 13 len1 = len(haystack) 14 len2 = len(needle) 15 if len2 == 0: 16 return haystack 17 pi = self.KMP(needle) 18 k = 0 19 for i in range(0, len1): 20 while k > 0 and needle[k] != haystack[i]: 21 k = pi[k-1] 22 if haystack[i] == needle[k]: 23 k += 1 24 if k == len2: 25 return haystack[i-len2+1:] 26 return None
3. Pow(x, n)(https://oj.leetcode.com/problems/powx-n/)
解法:利用二分来递归求解,注意n为负数的情况。时间复杂度O(log(n))
1 def pow(self, x, n): 2 if n == 0: 3 return 1 4 if n < 0: 5 return 1.0/pow(x, n*(-1)) 6 if n%2: 7 return self.pow(x*x, n/2)*x 8 else: 9 return self.pow(x*x, n/2)
4. sqrt(x)(https://oj.leetcode.com/problems/sqrtx/)
解法一:二分法:由于返回的是整数,这里可以考虑使用二分查找。查找的起点s=1, 由于(x/2+1)^2>x,终点设为x/2+1
1 def sqrt(self, x): 2 if x == 0: 3 return 0 4 s = 1 5 e = x/2 + 1 6 while s <= e: 7 mid = (s+e)/2 8 if mid**2 == x: 9 return mid 10 elif mid**2 < x: 11 s = mid + 1 12 else: 13 e = mid -1 14 return e
解法二:牛顿迭代法
f(y) = x - y^2 (sqrt(x) = y, x = y^2), 有牛顿迭代法 y = (y0 + x/y0)/2
1 def sqrt(self, x): 2 y0 = 1 3 y = (y0*1.0 + x*1.0/y0)/2.0 4 while int(y) != int(y0): 5 y0 = y 6 y = (y0*1.0 + x*1.0/y0)/2.0 7 return int(y)