Leetcode 的python解答收集
2017.9.7
距离开学还有一周,这个暑假刷完coursera上Andrew大神的machine learning(助学金),deeplearning.ai的course1(助学金),芭芭拉教授的Learn how to learn(旁听),华盛顿大学的Machine Learning Foundation(旁听)。一门Algorithm加在旁听里面,但是还没开始看。明天开始看吧,今天在家里实在没激情写代码。
今天健身有点累,不想刷leetcode,于是写一篇随笔记录一下leetcode上题目的python答案,就当熟悉一下Python。
1.Two Sum
class Solution(object): def twoSum(self, nums, target): dictnums={} for i in range(len(nums)): for j in range(len(nums)): if (nums[i]+nums[j])==target and (i!=j): return [i,j]
class Solution(object): def addTwoNumbers(self, l1, l2): root=n=ListNode(0) carry=0 while l1 or l2 or carry: v1=v2=0 if l1: v1=l1.val l1=l1.next if l2: v2=l2.val l2=l2.next carry,val=divmod(v1+v2+carry,10) n.next=ListNode(val) n=n.next return root.next
3.Longest Substring Without Repeating Characters
class Solution(object): def lengthOfLongestSubstring(self, s): start = maxlength= 0 usedword={} for i in range((len(s))): if s[i] in usedword and start<=usedword[s[i]]: start = usedword[s[i]] + 1 else : maxlength=max(maxlength,i+1-start) usedword[s[i]]=i return maxlength
4.Median of Two Sorted Arrays
class Solution(object): def findMedianSortedArrays(self, A,B): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ m=len(A);n=len(B) if m > n: A,B,m,n = B,A,n,m if n==0: raise ValueError imin,imax,half_len = 0, m,(m+n+1)/2 while (imin <= imax): i=(imin+imax)/2 j=half_len - i if i < m and B[j-1]>A[i]: #i is too small imin=i+1 elif i > 0 and B[j]<A[i-1]: #i is too big imax=i-1 else : #found i if i==0: left_max = B[j-1] elif j==0: left_max = A[i-1] else : left_max = max(A[i-1],B[j-1]) if (m+n)%2==1 : return left_max if i==m: right_min = B[j] elif j==n: rignt_min = A[i] else: right_min = min(A[i],B[j]) return (left_max+right_min)/2.0
5.Longest Palindromic Substring
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s)==0: return 0 maxlen = 1 start = 0 for i in xrange(len(s)): if i-maxlen >=1 and s[i-maxlen-1:i+1]==s[i-maxlen-1:i+1][::-1]: start = i - maxlen -1 maxlen +=2 continue if i-maxlen >=0 and s[i-maxlen:i+1]==s[i-maxlen:i+1][::-1]: start = i - maxlen maxlen +=1 return s[start:start+maxlen]
6.
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1 or numRows >= len(s): return s L = [''] * numRows index, step = 0, 1 for x in s: L[index] += x if index == 0: step = 1 elif index == numRows -1: step = -1 index += step return ''.join(L)
7.Reverse Integer
class Solution(object): def reverse(self, x): result = 0 sign = -1 if (x < 0) else 1 x=abs(x) while x!=0: tail = x% 10 newResult = result * 10 +tail result = newResult x = x/ 10 return result*sign*(result < 2**31)
9. Palindrome Number
class Solution(object): def isPalindrome(self, x): x=str(x) i=0;j=len(str(x))-1 while j > i: if (x[i]==x[j]): i=i+1 j=j-1 pass else : return False return True
13. Roman to Integer
class Solution(object): def romanToInt(self, s): roman={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1} z=0 for i in range(len(s)-1): if roman[s[i]] < roman[s[i+1]]: z-=roman[s[i]] else: z+=roman[s[i]] return z+roman[s[-1]]
14. longest Common Prefix
class Solution(object): def longestCommonPrefix(self, strs): if not strs: return "" for i,letter_group in enumerate(zip(*strs)): if len(set(letter_group))>1: return strs[0][:i] else: return min(strs)
20. Valid Parentheses
class Solution(object): def isValid(self, s): stack = [] dict = {"]":"[" , "}":"{" , ")":"("} for char in s : if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else : return False return stack == []
21. Merge Two Sorted Lists
class Solution(object): def mergeTwoLists(self, l1, l2): dummpy = cur = ListNode(0) while l1 and l2: if l1.val<l2.val: cur.next=l1 l1=l1.next else : cur.next=l2 l2=l2.next cur = cur.next cur.next = l1 or l2 return dummpy.next
26. Remove Duplicates from Sorted Array
class Solution(object): def removeDuplicates(self, A): if not A: return 0 newTail = 0 for i in range(1,len(A)): if A[i] != A[newTail]: newTail +=1 A[newTail] = A[i] return newTail + 1
27. Remove Element
class Solution(object): def removeElement(self, nums, val): begin = 0 for i in range(len(nums)): if nums[i]!=val: nums[begin]=nums[i] begin +=1 return begin
35. Search Insert Position
class Solution(object): def searchInsert(self, nums, target): begin = 0 if not nums: return None for i in range(len(nums)): if nums[i] == target: return i elif target > nums[i]: begin += 1 return begin
??:Length of last word
class Solution(object): def lengthOfLastWord(self, s): slen = 0 tail = len(s) - 1 while(tail >= 0 and s[tail] == ' '):tail-=1 while(tail >= 0 and s[tail] != ' '): slen+=1 tail-=1 return slen
66.Plus one
class Solution(object): def plusOne(self, digits): for i in range(len(digits))[::-1]: if digits[i]<9:digits[i]+=1;return digits else: digits[i]=0 digits.append(0) digits[0]=1 return digits
561.Array Partition I
class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ return sum(sorted(nums)[::2])
566. Reshape the Matrix
Solution 1 - NumPy When I read "MATLAB", I immediately thought "NumPy". Thanks to @fallcreek for tolist, makes converting the result to the correct type easier than what I had originally. ________________________________________ import numpy as np class Solution(object): def matrixReshape(self, nums, r, c): try: return np.reshape(nums, (r, c)).tolist() except: return nums Solution 2 - Oneliner An ugly oneliner :-) ___________________________________ def matrixReshape(self, nums, r, c): return nums if len(sum(nums, [])) != r * c else map(list, zip(*([iter(sum(nums, []))]*c))) ________________________________________ A more readable version of that: def matrixReshape(self, nums, r, c): flat = sum(nums, []) if len(flat) != r * c: return nums tuples = zip(*([iter(flat)] * c)) return map(list, tuples) Solution 3 - itertools def matrixReshape(self, nums, r, c): if r * c != len(nums) * len(nums[0]): return nums it = itertools.chain(*nums) return [list(itertools.islice(it, c)) for _ in xrange(r)]
485.Max Consecutive Ones
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ cnt = 0 ans = 0 for num in nums: if num == 1: cnt += 1 ans = max(ans,cnt) else: cnt = 0 return ans
88. Merge Sorted Array
def merge(self, nums1, m, nums2, n): while m > 0 and n > 0: if nums1[m-1] >= nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if n > 0: nums1[:n] = nums2[:n]
38.Count and Say
def countAndSay(self, n): s = '1' for _ in range(n - 1): s = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(s)) return s
67.Add Binary
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ if len(a)==0 : return b if len(b)==0 : return a if a[-1]=='1' and b[-1]=='1': return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0' if a[-1]=='0' and b[-1]=='0': return self.addBinary(a[0:-1],b[0:-1])+'0' else: return self.addBinary(a[0:-1],b[0:-1])+'1'
69.sqrt(x)
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ r=x while r*r>x: r= (r + x/r)/2 return r
83. Remove Duplicates from Sorted List
def deleteDuplicates(self, head): cur = head while cur: while cur.next and cur.next.val == cur.val: cur.next = cur.next.next # skip duplicated node cur = cur.next # not duplicate of current node, move to next node return head
100. Same Tree
class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p and q: return (p.val==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)) return p is q
101. Symmetric Tree
class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def isSym(L,R): if (not L and not R):return True if L and R and L.val==R.val: return isSym(L.left,R.right) and isSym(L.right,R.left) return False return isSym(root,root)

浙公网安备 33010602011771号