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 來源:简书
相关文章
相关标签/搜索