• leetcode 题库解答


     
     NO-001
    class Solution:
        '''
    两数和 哈希
    '''
    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_python

    1、Two Sum

     
    Two Sum.png

    这道题的解题思路很简单,利用python中的字典记录记录下每个元素出现的位置,也就是其他语言中的哈希表。

    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
    

    26、Remove Duplicates from Sorted Array

     
    Remove Duplicates from Sorted Array.png

    这道题要注意的是,不仅要返回不同元素的个数,而且要保证这n个数按照元顺序在数组的前n个位置,也不难,只要按顺序遍历一遍数组即可。

    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
    

    27、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
    

    35、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
    

    53、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
    

    66、 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)]
    

    88、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]
    

    118、Pascal's Triangle

     
    Pascal's Triangle.png

    著名的杨辉三角问题,本来想用笨办法,一行一行的循环生成,但是看到解题思路中一种比较独特的思路:
    1 3 3 1 0

    • 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
    

    119、Pascal's Triangle II

     
    Pascal's Triangle II.png

    按照上一题的思路即可:

    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
    

    121、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
    

    122、Best Time to Buy and Sell Stock II

     
    Best Time to Buy and Sell Stock II.png

    这道题比较简单,因为没有买卖次数限制,也没有买卖时间限制,如果后面的股价比前面的大,我们就买卖

    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))
    

    167、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
    來源:简书
     
  • 相关阅读:
    asp.net2.0系列视频教程
    Android入门教程(三十一)SQLite分页读取(转)
    sql语句大全
    判断是不是ie浏览器 加上ie11
    字节面试题
    泛型
    线程和
    sysbench工具
    自定义集合类
    类型通配符
  • 原文地址:https://www.cnblogs.com/koafan-zou/p/9327006.html
Copyright © 2020-2023  润新知