Personal Leetcode solution(Python) 21-35
个人刷Leetcode的一点解法,欢迎批评讨论,每日更新
GitHub:
https://github.com/seventheli/LeetCode-PracticeExcel Sheet Column Number
Reference:
ord(...)
ord(c) -> integer
Return the integer ordinal of a one-character string.
class Solution(object): def titleToNumber(self, s): """ :type s: str :rtype: int """ s = s.upper() list_n = list(s) output = 0 for each in list_n: output += ord() - ord('A') + 1 return output
Valid Anagram
Core: Two pointer
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ list_s = list(s) list_t = list(t) list_s.sort() list_t.sort() if list_s == list_t: return True else: return False
Integer Break
Core: Math or Dynamic Programming
Reference:
Math: https://discuss.leetcode.com/topic/43055/why-factor-2-or-3-the-math-behind-this-problem
Dynamic Programming:
Math Solution:
class Solution(object): def integerBreak(self, n): """ :type n: int :rtype: int """ if n == 2: return 1 if n == 3: return 2 trace = n % 3 index = n / 3 if trace == 1: return 4*(3**(index-1)) elif trace == 2: return 2*(3**index) else: return 3**index
First Unique Character in a String
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ list_s = list(s) dir_s = {} for i in xrange(len(list_s)): if list_s[i] in dir_s: dir_s[list_s[i]][0] += 1 else: template = [1, i] dir_s[list_s[i]] = template return_val = len(list_s) for each in dir_s: if dir_s[each][0] == 1 and dir_s[each][1] < return_val: return_val = dir_s[each][1] if return_val != len(list_s): return return_val else: return -1
Contains Duplicate
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ set_nums = set(nums) if len(set_nums) == len(nums): return False else: return True
Intersection of Two Arrays II
Core: Collection library, for follow up 3, read list2 as stream
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ import collections dir_1 = collections.Counter(nums1) result = [] for each in nums2: if each in dir_1 and dir_1[each] > 0: result.append(each) dir_1[each] -= 1 return result
Best Time to Buy and Sell Stock II
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ total = 0 for each in xrange(len(prices)-1): total += max(prices[each+1] - prices[each], 0) return total
Missing Number
Core: A XOR A = 0,0 XOR A = A
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ output = len(nums) for i in xrange(0,len(nums)): output ^= i output ^= nums[i] return output
Other Solution in JAVA: https://discuss.leetcode.com/topic/23427/3-different-ideas-xor-sum-binary-search-java-code/17
Roman to Integer
Core: Trun around the input roman number and translate it to integer
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ total = 0 template = 0 dir_roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} s = list(s)[::-1] for i in s: if dir_roman[i] >= template: total += dir_roman[i] template = dir_roman[i] else: total -= dir_roman[i] template = 0 return total
Binary Watch
Core: Translate all possible number for 0:00 to 11:59 to binary number and traval it
class Solution(object): def readBinaryWatch(self, num): """ :type num: int :rtype: List[str] """ output = [] for h in xrange(12): for m in xrange(60): if (bin(h) + bin(m)).count('1') == num: output.append('%d:%02d' % (h, m)) return output
Binary Tree Inorder Traversal
Core: Stack, Recursion
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ result, stack = [], [(root, False)] while stack: current, visited = stack.pop() if current: if visited: result.append(current.val) else: stack.append((current.right, False)) stack.append((current, True)) stack.append((current.left, False)) return result
Reverse Linked List
Core: Recursion
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ rev = None while head: head.next, rev, head = rev, head, head.next return rev
Count Numbers with Unique Digits
Core: f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0
class Solution(object): def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ n = min(n, 9) last = 0 cache = 0 prod = 1 for index in range(1, n): cache = index * prod cache += last last = cache prod *= (10 - index) return (10 * prod + cache) if n > 0 else 1
Majority Element
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ if nums is None or len(nums) == 0: raise Exception("Invalid Input") dc = dict() for each in nums: if each in dc: dc[each] += 1 else: dc[each] = 1 for each in dc: if dc[each] >= (len(nums) / 2.0): return each
Kth Smallest Element in a Sorted Matrix
Core: binary search
import bisect class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ lo, hi = matrix[0][0], matrix[-1][-1] while lo < hi: mid = (lo + hi) // 2 if sum(bisect.bisect_right(row,mid) for row in matrix) < k: lo = mid+1 else: hi = mid return lo
浙公网安备 33010602011771号