leetcode 題庫解答

class Solution: 
 NO-001
    '''
兩數和 哈希
'''
def twoSum(self,nums,target):
dict = {}
for i in range(len(nums)):
v = nums[i]
if target-v in dict:
return dict[target-v],i
dict[v]=i



nums = [3,2,4,8]
target = 6
Solution().twoSum(nums,target)


class Leetcode_Solution(object):
  def reverse_7(self,x): """ :type x: int :rtype: int """ MAX = 2**31 - 1 min = -1*2**31 if x < 0: y = -1*int(str(-x)[::-1]) else: y = int(str(x)[::-1]) if y > Max or y < min: return 0 return y def isPalindrome_9(self, x): renum = 0 if x < 0 or (x % 10 == 0 and x != 0): return False while x > renum: renum = renum * 10 + x % 10 x /= 10 return x == renum or x == renum/10 def romanToInt_13(self, s): """ :type s: str :rtype: int """ dic = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} sum = 0 for i in range(len(s)-1): if dic[s[i]] < dic[s[i+1]]: sum -= dic[s[i]] else: sum += dic[s[i]] return sum + dic[s[-1]] def longestCommonPrefix_14(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: # Horizontal scanning/////another way: vertical scanning return '' prefix = strs[0] for i in range(1,len(strs)): while strs[i].find(prefix) != 0: prefix = prefix[0:len(prefix)-1] if prefix == '': return '' return prefix def isValid_20(self, s): """ :type s: str :rtype: bool """ ''' list = [] a = b = c = 0 if len(s) == 0: return True for i in range(len(s)): if s[i] == '(': list.append(s[i]) a += 1 if s[i] == '{': list.append(s[i]) b += 1 if s[i] == '[': list.append(s[i]) c += 1 if s[i] == ')': if len(list) != 0 and list[-1] == '(': list.pop() a -= 1 else: return False if s[i] == '}': if len(list) != 0 and list[-1] == '{': list.pop() b -= 1 else: return False if s[i] == ']': if len(list) != 0 and list[-1] == '[': list.pop() c -= 1 else: return False if len(list) == 0 and a == b == c == 0: return True else: return False ''' dic = {')':'(','{':'}','[':']'} stack = [] for i in s: if i in dic.values(): stack.append(i) elif i in dic.keys(): if stack == [] or dic[i] != stack.pop(): return False else: return False return stack == [] def mergeTwoLists_21(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None head = rear = ListNode(0) while l1 and l2: if l1.val < l2.val: rear.next = l1 l1 = l1.next else: rear.next = l2 l2 = l2.next rear = rear.next rear.next = l1 or l2 return head.next def removeDuplicates_26(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 newtail = 0 for i in range(1,len(nums)): if nums[i] != nums[newtail]: newtail += 1 nums[newtail] = nums[i] return newtail + 1 def removeElement_27(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i = len(nums) j = 0 if i == 0: return 0 while j < i: if nums[j] == val: nums.pop(j) i -= 1 else: j += 1 return len(nums) def strStr_28(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle) +1): if haystack[i:i+len(needle)] == needle: return i return -1 def searchInsert_35(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ return len([x for x in nums if x < target]) def countAndSay(self, n): """ :type n: int :rtype: str """


第一遍刷題的時候過得速度比較快,由於我以爲基礎很差的我,不要硬着頭皮去想最優的方法,而是應該儘可能去學一些算法思想,因此每道題只給本身5-10分鐘的時間想,想不出來的就去找相關的答案,因此刷的比較快。

個人github鏈接:https://github.com/princewen/leetcode_pythonpython

一、Two Sum

 
Two Sum.png

這道題的解題思路很簡單,利用python中的字典記錄記錄下每一個元素出現的位置,也就是其餘語言中的哈希表。git

class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic = dict() for index,value in enumerate(nums): sub = target - value if sub in dic: return [dic[sub],index] else: dic[value] = index 

2六、Remove Duplicates from Sorted Array

 
Remove Duplicates from Sorted Array.png

這道題要注意的是,不只要返回不一樣元素的個數,並且要保證這n個數按照元順序在數組的前n個位置,也不難,只要按順序遍歷一遍數組便可。github

class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 index = 0 for i in range(1, len(nums)): if nums[i] != nums[index]: index = index + 1 nums[index] = nums[i] return index + 1 

2七、Remove Element

 
Remove Element.png

思路同上一題,遍歷一遍數組便可面試

class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ index = 0 for i in range(0,len(nums)): if nums[i] != val: nums[index] = nums[i] index = index + 1 return index 

3五、Search Insert Position

 
Search insert position.png

對於排好序的數組進行插入的問題,爲了減少算法的時間複雜度,很容易想到用二分查找的方法:算法

class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ left = 0 right = len(nums)-1 while left <= right: mid = (right - left) / 2 + left if nums[mid] == target: return mid elif nums[mid] > target: right = mid - 1 else: left = mid + 1 return left 

5三、Maximum Subarray

 

 
Maximum Subarray.png

這道題跟以前我在網易面試的股票買賣問題相似,採用的叫 Kadane's Algorithm的方法,用兩個指針。maxSum指針記錄此前全部碰到的最大值,curSum指針記錄循環到當前元素這一輪的最大值。當循環到元素i時,若是i+curSum < i的話,說明此前的和是負的,須要捨棄,因此將curSum的值變爲i,反之,將curSum的值變爲i+curSum,代表當前的和仍是正值,能夠繼續向前探索,因爲每一次遍歷一個元素以後都會比較一下curSum和maxSum,因此能夠放心的繼續向前遍歷。

 

class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] ![Plus One.png](//upload-images.jianshu.io/upload_images/4155986-52d077924ae34aff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) :rtype: int """ curSum=maxSum=nums[0] for i in range(1,len(nums)): curSum = max(nums[i],curSum+nums[i]) maxSum = max(curSum,maxSum) return maxSum 

6六、 Plus One

 
Plus One.png

原本想的是從最後一位,找一個記錄當前進位的變量,而後遍歷一遍數組,後來看了答案,是利用字符串和int的轉換作的,解法以下:數組

class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ sum = 0 for i in digits: sum = sum * 10 + i return [int(x) for x in str(sum+1)] 

8八、Merge Sorted Array

 
Merge Sorted Array.png

這道題很天然的想法就是從後往前遍歷兩個數組,而後把對應的元素放在數組1對應的位置,惟一須要注意的是最後咱們只需判斷數組2有沒有遍歷完便可,由於數組1沒有遍歷完的話,它已是按順序放在前面的了:微信

class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ while m > 0 and n > 0: if nums1[m - 1] > nums2[n - 1]: nums1[m + n - 1] = nums1[m - 1] m = m - 1 else: nums1[m + n - 1] = nums2[n - 1] n = n - 1 if n > 0: nums1[:n] = nums2[:n] 

11八、Pascal's Triangle

 
Pascal's Triangle.png

著名的楊輝三角問題,原本想用笨辦法,一行一行的循環生成,可是看到解題思路中一種比較獨特的思路:
1 3 3 1 0markdown

  • 0 1 3 3 1
    = 1 4 6 4 1
    代碼以下:
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0:return [] res = [[1]] for i in range(1,numRows): res.append(map(lambda x,y:x+y,res[-1]+[0],[0]+res[-1])) return res 

11九、Pascal's Triangle II

 
Pascal's Triangle II.png

按照上一題的思路便可:app

class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ res = [1] for i in range(1, rowIndex + 1): res = list(map(lambda x, y: x + y, res + [0], [0] + res)) return res 

12一、Best Time to Buy and Sell Stock

 

 
Best Time to Buy and Sell Stock.png

相似於53題的思路,使用 Kadane's Algorithm

 

class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ curSum=maxSum=0 for i in range(1,len(prices)): curSum=max(0,curSum+prices[i]-prices[i-1]) maxSum = max(curSum,maxSum) return maxSum 

12二、Best Time to Buy and Sell Stock II

 
Best Time to Buy and Sell Stock II.png

這道題比較簡單,由於沒有買賣次數限制,也沒有買賣時間限制,若是後面的股價比前面的大,咱們就買賣post

class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ return sum(max(prices[i+1]-prices[i],0) for i in range(len(prices)-1)) 

16七、Two Sum II - Input array is sorted

 
Two Sum II - Input array is sorted

仍然可使用第一題的思路:

class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ res = dict() for i in range(0,len(numbers)): sub = target - numbers[i] if sub in res.keys(): return [res[sub]+1,i+1] else: res[numbers[i]] = i return [] 

微信 sxw2251

連接:https://www.jianshu.com/p/b71fc7307e42 來源:簡書
相關文章
相關標籤/搜索