3个月用python刷完leetcode600题!-数组简单题(一)

十五天的时间,刷完了所有的简单题,避免遗忘,所以开始简单题的二刷,第一遍刷题的时候过得速度比较快,因为我觉得基础不好的我,不要硬着头皮去想最优的方法,而是应该尽量去学一些算法思想,所以每道题只给自己5-10分钟的时间想,想不出来的就去找相关的答案,所以刷的比较快。二刷的时候按照leetcode官方给出的题目分类展开,同时,将解题思路记录于简书加深印象。
想要一起刷题的小伙伴,我们一起加油吧!
我的github连接:https://github.com/princewen/leetcode_python

1、Two Sum

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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](http://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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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

《3个月用python刷完leetcode600题!-数组简单题(一)》 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 []

如果大家对leetcode感兴趣,欢迎跟小编进行交流,小编微信为sxw2251,加我要写好备注哟!:

《3个月用python刷完leetcode600题!-数组简单题(一)》 我的微信

微信公众号

《3个月用python刷完leetcode600题!-数组简单题(一)》

    原文作者:石晓文的学习日记
    原文地址: https://www.jianshu.com/p/b71fc7307e42
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞