Leetcode题目练习总结(持续更新......)

Leetcode题目练习

  • 数组
    • 1.两数之和
    • 26. 删除排序数组中的重复项
    • 27. 移除元素
    • 35.搜索插入位置
    • 53.最大子序列
    • 66.加一
    • 88.合并两个有序数组
    • 118.杨辉三角
    • 119.杨辉三角2
    • 121.买卖股票的最佳时机
    • 122.买卖股票的最佳时机2
    • 167.两数之和2
    • 169.多数元素
    • 189.旋转数组
    • 217.存在重复元素
    • 219.存在重复元素2
    • 268.缺失数字
    • 283.移动零
    • 414.第三大的数
    • 448.找到所有数组中消失的数字
    • 485.最大连续1的个数
    • 509.斐波那契数
    • 532.数组中的K-diff数对
    • 561.数组拆分
    • 566.重塑矩阵
    • 581.最短无序连续子数组
    • 605.种花问题
    • 628.三个数的最大乘积
    • 643.子数组最大平均数
    • 661.图片平滑器
    • 921.使括号有效的最少添加

数组

1.两数之和

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

python解答:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        data = {}
        for i, n in enumerate(nums):
            # data[n] = i
            if target-n in data:
                return [data[target-n], i]
            data[n] = i

答案解析:本题的关键点在于,需要想到如何查询,是否存在两个数的和等于目标值,即求当给出一个数,数组中是否存在另一个数等于目标值-这个数。为了更加有效率,使用字典的形式。注意:这里的data[n]=i一定需要放在if函数后面,这是防止出现类似目标值为6,其中数组中一个数为3的现象。

26. 删除排序数组中的重复项

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

python解答:

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

答案解析:首先需要注意题意说的是排序数组,那么数组中的每一个元素比较之后,只需要继续比较后面的数值即可,无需重复比较。

27. 移除元素

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

python解答:

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

答案解析:本题类似于26,只需要使用两个指针,将不为目标值的数值存储到数组中,即可起到对应的目的。

35.搜索插入位置

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

python解答:

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

答案解析:本题使用的是二分法搜索,相比较一个个顺序搜索,会极大地节省时间,本题需要注意的就是left(i)和right(j)下标移动的时候,mid是否需要增加减少1,可以试一下会发现,如果不减1或增1,会陷入while循环。

53.最大子序列

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

python解答:

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        last_sum = nums[0]
        sub = 0
        for item in nums:
            sub = max(sub + item, item)
            last_sum = max(last_sum, sub)
        return last_sum

答案解析:本题采用的是动态规划方法,类似于“滚动数组”的思想。

66.加一

Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

python解答:

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        for i in range(len(digits)-1, -1, -1):
            if digits[i] != 9:
                digits[i] += 1
                return digits
            digits[i] = 0
        ans = [0]*(len(digits)+1)
        ans[0] = 1
        return ans

答案解析:本题解答的巧妙之处在于一旦末尾数字为9,则自动加一,并且原位置归0。而如果所有位置都为9,则全部设为0,最后数组长度加一,首位设为1即可。

88.合并两个有序数组

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3
Output: [1,2,2,3,5,6]

Constraints:

-10^9 <= nums1[i], nums2[i] <= 10^9
nums1.length == m + n
nums2.length == n

python解答:

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: None Do not return anything, modify nums1 in-place instead.
        """
        nums3 = nums1[:m]
        nums1[:] = []
        i, j = 0, 0
        while i < m and j < n:
            if nums3[i] < nums2[j]:
                nums1.append(nums3[i])
                i += 1
            else:
                nums1.append(nums2[j])
                j += 1
        if i < m:
            nums1[i+j:] = nums3[i:]
        if j < n:
            nums1[i+j:] = nums2[j:]

答案解析:本题的思路是首选复制nums1数组,然后将nums1数组清空,按照各个数组的大小顺序依次加入到nums1数组中,最后再将某一数组中剩下的元素全部加入到nums1数组内。

118.杨辉三角

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

python解答:

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        triangle = []
        for num in range(0, numRows):
            row = [None for i in range(num+1)]
            row[0], row[-1] = 1, 1
            for i in range(1, len(row)-1):
                row[i] = triangle[num-1][i-1]+triangle[num-1][i]
            triangle.append(row)

        return triangle

答案解析:三角结构中,首先可以注明第一个和最后一个元素都为0,其余的每一个元素都是上一行对应的三角形中的两个元素相加。

119.杨辉三角2

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Note that the row index starts from 0.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

python解答:

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        triangle = []
        for i in range(0, rowIndex+1):
            row = [None for _ in range(0, i+1)]
            row[0], row[-1] = 1, 1
            for j in range(1, i):
                row[j] = triangle[i-1][j-1] + triangle[i-1][j]
            triangle.append(row)
        return triangle[rowIndex]

答案解析:本题和118题思路是一样的,就是需要注意一下第一个循环里,应该是rowIndex+1,否则输出的其实是rowIndex-1行的内容,出现错误。

121.买卖股票的最佳时机

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

python解答:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        minprice = int(1e9)
        maxprice = 0 
        for price in prices:
            maxprice = max(price-minprice, maxprice)
            minprice = min(price, minprice)
        return  maxprice

答案解析:本题的思路是搜寻到历史最低纪录,在历史最低处购买,在未来最高的某天卖出即可,如果依次遍历,在leetcode上运行会显示超时。

122.买卖股票的最佳时机2

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Constraints:

1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4

python解答:

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

答案解析:本题暴力解法相对复杂,最优解反而最易想到,即判断前后值大小,类似于峰值和低谷,并将其差值相加即可。

167.两数之和2

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

python解答:

# 双指针法
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
		low = 0
        high = len(numbers)-1
        while (low < high):
            num_type = numbers[low] + numbers[high]
            if num_type == target:
                return low+1, high+1
            elif num_type < target:
                low += 1
            else:
                high -= 1
## 二分法
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(numbers)
        for i in range(len(numbers)):
            low = i + 1
            high = n - 1
            while(low <= high):  
                mid = low + (high - low)/2
                if numbers[mid] == (target-numbers[i]):
                    return i+1, mid+1
                elif numbers[mid] < (target-numbers[i]):
                    low = mid + 1
                else:
                    high = mid - 1
        return [-1, -1]

答案解析:本题运行效果来看似乎是双指针法更高效率,但是实际上二分法在数据极多的情况下,会首先排除一半的元素,效率更高一些。而且,二分法需要注意的是low=mid+1/high=mid-1,这样可以防止重复用某些元素。

169.多数元素

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

python解答:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # counts = collections.Counter(nums)
        # return max(counts.keys(), key=counts.get)
        candidate = nums[0]
        num = 0
        for i in range(len(nums)):
            if num == 0:
                candidate = nums[i]
            if candidate == nums[i]:
                num += 1
            else:
                num -= 1
        return candidate

答案解析:最开始注释的两行是一般的使用哈希表来记下每个元素的数量,最后输出最大数量的元素即可,时间复杂度较高。第二种方法是投票法,通过投票最后肯定是众数胜利的原理,用candidate来作为候选众数。

189.旋转数组

Given an array, rotate the array to the right by k steps, where k is non-negative.

Follow up:

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

python解答:

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        k = k % len(nums)
        def reverse(arr, start, end):
            while start < end:
                inter = arr[end]
                arr[end] = arr[start]
                arr[start] = inter
                start += 1
                end -= 1
        reverse(nums, 0, len(nums)-1)
        reverse(nums, 0, k-1)
        reverse(nums, k, len(nums)-1)

答案解析:本题采用的是反转法,也就是分三次翻转,首先把所有的元素前后翻转,然后把前k个元素前后翻转,最后把后n-k个元素前后翻转。

217.存在重复元素

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

python解答:

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        dict1 = {}
        i = 0
        for n in nums:
            if n not in dict1:
                dict1[n] = i
                i += 1
            else:
                return True
        return False 

答案解析:本题很容易想到使用字典,类似于Java中的哈希表,先将未出现过的元素加入到dict中,一旦有个元素已经在dict中,则说明出现了重复元素,即可返回true。

219.存在重复元素2

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

python解答:

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dict1 = {}
        m = False
        for i, n in enumerate(nums):
            if n in dict1:
                if (i - dict1[n]) <= k:
                    m = True
                else:
                    dict1[n] = i
            elif n not in dict1:
                dict1[n] = i
        return m

答案解析:本题我只用了一个字典来存储数组的元素,维护一个m值,当重复元素出现的时候,比较它和上一个元素的index差值即可,内存消耗打败了100%的用户。这一题很容易解决,但是容易出错在理解题意上,我最初的理解是求最小的两个重复元素index的差值即可,后来没有通过,才仔细看了一下例子,发现是任意两个重复的元素的index的绝对值都不能大于k。

268.缺失数字

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

python解答:

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # nums.sort()
        # for i, n in enumerate(nums):
        #     if i != n:
        #         return i
        # return len(nums)
        dict1 = set(nums)
        for i in range(len(nums) + 1):
            if i not in dict1:
                return i

答案解析:本题注释的部分采用的是首先将数组排序,之后index和元素不同的即返回。或者使用哈希表类的方式,直接看是否有对应的数字在数组内。官方给出了另一种很巧妙的方式,就是利用数学法,数组内数字补全的时候和减去实际上数组的和,即为所缺失的数字。

283.移动零

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

python解答:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        stack = 0
        for i in range(len(nums)):
            if nums[i] == 0:
                stack += 1
            else:
                nums[i-stack] = nums[i]
        nums[len(nums)-stack:] = [0] * stack

答案解析:本题的官方解释写的很模糊,也很难得出官方一定是最优的,所以这是我个人的解答,但是运行时间也超过92%的用户。我的思想是最后是要把元素排除掉0而不打乱位置,那也就是这个原有元素前面有几个0,就往前移几个位置,这里面的stack一直纪录出现0的数量,到最后有几个0 ,就直接让数组最后的几个元素为0即可。

414.第三大的数

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

python解答:

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # list1 = []
        # for num in nums:
        #     if num not in list1:
        #         list1.append(num)
        # list1.sort()
        # if len(list1) < 3:
        #     return list1[-1]
        # else:
        #     return list1[-3]
        list1 = set(nums)
        if len(list1) < 3:
            return max(list1)
        else:
            list1.remove(max(list1))
            list1.remove(max(list1))
            return max(list1)

答案解析:本题最开始的思路是注释掉的那部分,也就是先将元素依次存储在新的列表中,然后排序,返回第三个数字,但是时间复杂度较高,需要500ms。参考了评论的解题方法,使用set和remove来去重和返回第三大数字。

448.找到所有数组中消失的数字

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

python解答:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        # dict1 = set(nums)
        # list1 = []
        # if len(nums) == 0:
        #     return []
        # for i in range(0, len(nums)):
        #     if (i + 1) not in dict1:
        #         list1.append(i+1)
        # return list1
        list1 = []
        for i in range(len(nums)):
            index = abs(nums[i]) - 1
            if nums[index] > 0:
                nums[index] *= -1 
        for i in range(len(nums)):
            if nums[i] > 0:
                list1.append(i+1)

        return list1

答案解析:注释掉的部分是首选对数组去重,之后依次看index哪个不在dict1中,则加入到列表中,最后返回。第二种方法没有使用额外的空间,如果某个元素存在,则让它作为index的对应的元素为负,最后数组中元素还为正的index+1则为缺失的数值。

485.最大连续1的个数

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

python解答:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count, res = 0, 0
        # list1 = []
        for num in nums:
            if num == 1:
                count += 1
            else:
                res = max(res, count)
                count = 0
        # list1.append(count)
        res = max(res, count)
        return res

答案解析:本题比较简单,其实就是当元素为1的时候,就设置一个count来记录出现的次数,当出现0的时候,就把count清零,最后保留最大的count值即可,时间复杂度为O(N)。

509.斐波那契数

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).

Example 1:

Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

python解答:

class Solution(object):
    def fib(self, N):
        """
        :type N: int
        :rtype: int
        """
        x1 = 1
        x2 = 1
        target = 0
        if N == 0:
            return 0
        elif N == 1 or N == 2:
            return 1
        for i in range(3, N+1):
            target = x1 + x2
            x1 = x2
            x2 = target
        return target

答案解析:本题如果使用迭代的方法,复杂度会很高,因为相当于每个数都重新计算一次。而如果使用两个变量来存储前面两个斐波那契数,则可以降低复杂度。

532.数组中的K-diff数对

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:

Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

python解答:

class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k < 0:
            return 0
        a, b = set(), set()
        for num in nums:
            if (num - k) in a:
                b.add(num - k)
            if (num + k) in a:
                b.add(num)
            a.add(num)
        return len(b)

答案解析:本题最关键的点是,每次只存储数对中的小的那个数字,这样可以保证不重复。

561.数组拆分

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

python解答:

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # nums.sort()
        # target = 0
        # for i in range(len(nums)):
        #     if i%2 == 0:
        #         target += nums[i]
        # return target
        dict1 = {}
        target = 0
        for num in nums:
            num += 10000
            if num not in dict1:
                dict1[num] = 1
            else:
                dict1[num] += 1
        d = 0
        for i in range(-10000, 10001):
            if (i+10000) in dict1:
                target += ((dict1[i + 10000] + 1 - d) // 2 * i)
                d = (dict1[i + 10000] - d + 2) % 2
        return target

答案解析:根据题目及提示,本题注释的部分是比较容易想到的,首先将数组排序,将奇数位的元素相加即可。另外,本题还有一种解法,即计数排序法,利用哈希表(字典)来依次计算小的元素的数量,如果它是偶数,那么它刚好等于它的数量/2*这个元素,如果是奇数,那么它下一个元素就要首选失去一,因为已经用于和前面这个小的元素配对了。

566.重塑矩阵

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

python解答:

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        target = []
        if len(nums) * len(nums[0]) != r * c:
            return nums
        else:
            list1 = []
            for num in nums:
                for element in num:
                    list1.append(element)
                    if len(list1) == c:
                        target.append(list1)
                        list1 = []
        return target

答案解析:本题的解题思路也比较简单,首先确认元素是否能重组成r行c列,确认可以之后就是依次取出原二维数组中的每个元素,按照每c个元素一组依次存入target中即可。

581.最短无序连续子数组

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

python解答:

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        list1 = nums[:]
        nums.sort()
        list2 = []
        for i in range(len(nums)):
            if nums[i] != list1[i]:
                list2.append(i)
        if len(list2) == 0:
            return 0
        else:
            return max(list2) - min(list2) + 1

答案解析:本题我的思路比较简单,就是首先对数组排序,之后根据那些位置变动了,最大的index减去最小的index即可。本题还可以考虑堆栈的思想,首选遍历数组,如果发现不是升序的元素,则看它应该在哪个位置,保留最小的那个index,之后逆序遍历一遍,得出最大的index,即可对应的求出。

605.种花问题

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.

python解答:

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        count = 0
        i = 0
        while(i <= (len(flowerbed)-1)):
            if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and (i== len(flowerbed)-1 or flowerbed[i+1] == 0):
                count += 1
                flowerbed[i] = 1
            if count >= n:
                return True
            i += 1
        return False

答案解析:本题好像也没有很简单的解决方法,使用的就是普通的依次查询,这里面官方给出的条件查询语句是很巧妙的,包含了全部的情况,比如说当只有一个元素为0的时候,即len = 1, 这个时候i == 0 ,而且 i == len(flowerbed)-1,所以如果n <= 1,则返回True。

628.三个数的最大乘积

Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:

Input: [1,2,3]
Output: 6

Example 2:

Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

python解答:

class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # if len(nums) == 3:
        #     return(nums[0] * nums[1] * nums[2])
        # else:
        #     nums.sort()
        #     return max(nums[-1] * nums[0] * nums[1], nums[-1] * nums[-2] * nums[-3])
        if len(nums) == 3:
            return(nums[0] * nums[1] * nums[2])
        else:
            max1, max2, max3 = -1001, -1001, -1001
            min1, min2 = 1001, 1001
            for num in nums:
                if num > max1:
                    max3 = max2
                    max2 = max1
                    max1 = num
                elif num > max2:
                    max3 = max2
                    max2 = num
                elif num > max3:
                    max3 = num
                if num < min2:
                    min1 = min2
                    min2 = num
                elif num < min1:
                    min1 = num
            return max(max1 * max2 * max3, max1 * min1 * min2)

答案解析:本题注释的部分就是先将数组排序,那么考虑几种情况:全部为正数,则肯定是最后三个数相乘最大;全部为负数,那么肯定是最大的那三个负数相乘最大;有正数也有负数的情况下,有可能有三个正数存在,同时一个最大的正数乘上最小的两个负数,这两个里面一定有一个是最大的数,总之肯定都是最后三个数的乘积和前两个数和最后一个数的乘积取最大值即可。未注释的代码是官方给出的一种不需要排序的方法,就是记录三个最大值,和两个最小值,最后返回乘积最大值即可。

643.子数组最大平均数

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

python解答:

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        res = 0
        for i in range(0, k):
            res += nums[i]
        if k == len(nums):
            return float(res)/k
        else:
            sum_ite = res
            for i in range(0, len(nums)-k):
                sum_ite = sum_ite - nums[i] + nums[i + k]
                res = max(res, sum_ite)
            return 1.0*res/k

答案解析:本题使用的滑动窗口的方法,首选将数组前k个元素相加,染化依次每次减去第一个数,再加上后面那一个数字,保留最大的和即可。

661.图片平滑器

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

Example 1:

Input:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
Output:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Note:
The value in the given matrix is in the range of [0, 255].
The length and width of the given matrix are in the range of [1, 150].

python解答:

class Solution(object):
    def imageSmoother(self, M):
        """
        :type M: List[List[int]]
        :rtype: List[List[int]]
        """
        target = copy.deepcopy(M)
        for i in range(0, len(M)):
            for j in range(0, len(M[0])):
                total = 0
                num = 0
                for k in range(i-1, i+2):
                    for l in range(j-1, j+2):
                        # if k in range(0, len(M)) and l in range(0, len(M[0])):
                        if 0<= k < len(M) and 0 <= l < len(M[0]):
                        
                            total += M[k][l]
                            num += 1
                target[i][j] = total//num
        return target

答案解析:我这一题使用的方法效率并不高,但是胜在代码简单,就是每个元素的四周都算进来,只要对应坐标在范围内就加进去。(注:其中的条件,如果换成注释的话,时间就会增加很多)

921.使括号有效的最少添加

Given a string S of ‘(’ and ‘)’ parentheses, we add the minimum number of parentheses ( ‘(’ or ‘)’, and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

It is the empty string, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4

python解答:

class Solution(object):
    def minAddToMakeValid(self, S):
        """
        :type S: str
        :rtype: int
        """
        ans = bal = 0
        for symbol in S:
            bal += 1 if symbol == '(' else -1
            # It is guaranteed bal >= -1
            if bal == -1:
                ans += 1
                bal += 1
        return ans + bal

答案解析:按照括号顺序,首先是‘)’的话,bal保持为0,ans累加其出现的次数,如果是‘(’和‘)’依次出现的话,说明构成一个字符“()”,则不需要增加新的括号内容。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

你可能感兴趣的:(python)