Bootstrap

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

Leetcode题目练习

数组

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

498.对角线遍历

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

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

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

Explanation:
在这里插入图片描述

Note:
The total number of elements of the given matrix will not exceed 10,000.

python解答:

class Solution(object):
    def findDiagonalOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        # if len(matrix) == 0 or len(matrix[0]) == 0:
        #     return []
        # target = []
        # m = len(matrix)
        # n = len(matrix[0])
        # for d in range(0, m+n-1):
        #     list1 = []
        #     if d < n:
        #         r = 0
        #         c = d
        #     else:
        #         r = d-n+1
        #         c = n-1
        #     while r < m and c > -1:
        #         list1.append(matrix[r][c])
        #         r += 1
        #         c -= 1
        #     if d % 2 == 0:
        #         for item in list1[::-1]:
        #             target.append(item)
        #     else:
        #         for item in list1:
        #             target.append(item)
        # return target
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return []
        direction = 1  # 往上走
        m = len(matrix)
        n = len(matrix[0])
        i, j = 0, 0
        target = []
        while i < m and j < n:
            target.append(matrix[i][j])
            if direction == 1:
                row = i -1
                colomn = j + 1
            else:
                row = i + 1
                colomn = j - 1
            if row < 0 or row == m or colomn < 0 or colomn == n:
                if direction == 1:
                    if j == n-1:
                        i += 1
                    if j < n-1:
                        j += 1
                else:
                    if i == m-1:
                        j += 1
                    if i < m-1:
                        i += 1
                direction = 1 - direction
            else:
                i = row
                j = colomn
        return target

答案解析:本题使用了两种方法,注释的那一种是依次取出对角线的元素,然后按照一上一下的顺序,正序反序替换来取出各个对角线的元素。第二种方法就是依次进行条件判断,存入到数组中,第二种方法相比效率更高,但是条件判断更麻烦一点。

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

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

665.非递减数列

Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

Example 1:

Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: nums = [4,2,1]
Output: false
Explanation: You can't get a non-decreasing array by modify at most one element.

python解答:

if len(nums) == 1:
            return True
        count = 0
        for i in range(len(nums)-1):
            if nums[i] > nums[i+1]:
                count += 1
                if i != 0 and i != len(nums)-2:
                    if nums[i-1] > nums[i+1] and nums[i] > nums[i+2]:
                        return False
                if count >= 2:
                    return False
               
        return True

答案解析:本题思路本身不复杂,我在做题的时候主要是条件语句出现了问题。首先,就是看有多少个元素比后一个元素大,如果有两个及以上,则肯定不只需要一次元素修改,那么直接返回False。如果刚好有一个情况出现,那么检查出现的元素位置,如果是0或者len-2,那么肯定可以修改一个元素就能变成非递减,其余的情况则按代码中的条件判断即可。

674.最长连续递增序列

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

Example 1:

Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 

Example 2:

Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1. 

Note: Length of the array will not exceed 10,000.
python解答:

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

答案解析:本题思路很简单,无非就是滑动元素直到递增趋势被打破,然后记录此时的序列长度,依次往下,最后返回最大的长度即可。

697.数组的度

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: nums = [1,2,2,3,1]
Output: 2
Explanation: 
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation: 
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.

Constraints:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
python解答:

class Solution(object):
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left, right, count = {}, {}, {}
        for i in range(len(nums)):
            if nums[i] not in left:
                left[nums[i]] = i
            right[nums[i]] = i
            count[nums[i]] = count.get(nums[i], 0) + 1  # get(key, 0)意思是如果没找到key,则返回0
        target = 50000
        max_length = max(count.values())
        for n in count:
            if count[n] == max_length:
                target = min(target, right[n]-left[n]+1)
        return target

答案解析:用三个字典分别记录对应元素的最小index、最大index以及出现的次数,最后比较出现次数都为某一最大值的元素最小间隔即可。

717.1比特与2比特字符

We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Example 1:

Input: 
bits = [1, 0, 0]
Output: True
Explanation: 
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.

Example 2:

Input: 
bits = [1, 1, 1, 0]
Output: False
Explanation: 
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
Note:
1 <= len(bits) <= 1000.
bits[i] is always 0 or 1.

python解答:

class Solution(object):
    def isOneBitCharacter(self, bits):
        """
        :type bits: List[int]
        :rtype: bool
        """
        # i = 0
        # while i < len(bits) - 1:
        #     i += bits[i] + 1
        # return i == len(bits)-1
        
        ret = 0
        i = len(bits) - 2
        while bits[i] == 1 and i >= 0:
            ret += 1
            i -= 1
        return ret % 2 == 0

答案解析:注释掉的部分使用的方法比较简单,就是依次比较,如果遇见1,肯定要直接跳两个元素,如果为0,则1,最后比较得到的index是否为最后一个元素即可;第二种方法就是从倒数第二个元素直到出现一个0(如果倒数第二个元素就是0,则直接返回),其中如果出现奇数个1,则为False,反之则为True。

724.寻找数组的中心索引

Given an array of integers nums, write a method that returns the “pivot” index of this array.

We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Constraints:
The length of nums will be in the range [0, 10000].
Each element nums[i] will be an integer in the range [-1000, 1000].

python解答:

class Solution(object):
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        s = sum(nums)
        leftnum = 0
        for i in range(len(nums)):
            if leftnum == (s - leftnum - nums[i]):
                return i
            leftnum += nums[i]
        return -1

答案解析:本题一开始想使用从两边依次加起的方法,但是后来发现情况很多,很难完成。官方给出的答案比较简洁且有效,首选求数组的和,然后依次比较去掉某个元素左边及该元素后的和是否和左边元素的和相等。

746.使用最小花费爬楼梯

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
cost will have a length in the range [2, 1000].
Every cost[i] will be an integer in the range [0, 999].

python解答:

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        if len(cost) == 2:
            return min(cost)
        for i in range(2, len(cost)):
            cost[i] += min(cost[i-1], cost[i-2])
        return min(cost[-1], cost[-2])

答案解析:本题评论很多人说题意难理解,但是其实我个人觉得题意还是很好理解的,反而是没想到动态规划的问题,其实就是不断地进行前两个对应的最小花费的最小值,不断地迭代更新,直到最后两个元素的最小值得到,再输出其中最小的值即可。或者逆序计算花费,也是相同的道理。

747.至少是其他数字的两倍

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

Example 1:

Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.
Note:
nums will have a length in the range [1, 50].
Every nums[i] will be an integer in the range [0, 99].

python解答:

class Solution(object):
    def dominantIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:
            return 0
        if len(nums) == 2:
            if nums[1] >= 2*nums[0]:
                return 1
            if nums[0] >= 2*nums[1]:
                return 0
            return -1
        target = nums[:]
        nums.sort()
        if nums[-2] * 2 > nums[-1]:
            return -1
        else:
            return target.index(nums[-1])

答案解析:本题不复杂,其实只需要判断最大的数是否是第二大的数的二倍即可。

766.托普利茨矩阵

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.

Example 1:

Input:
matrix = [
  [1,2,3,4],
  [5,1,2,3],
  [9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

Input:
matrix = [
  [1,2],
  [2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.
Note:
matrix will be a 2D array of integers.
matrix will have a number of rows and columns in range [1, 20].
matrix[i][j] will be integers in range [0, 99].
Follow up:
What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
What if the matrix is so large that you can only load up a partial row into the memory at once?

python解答:

class Solution(object):
    def isToeplitzMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: bool
        """
        # if len(matrix) == 1 or len(matrix[0]) == 1:
        #     return True
        # i = 0
        # for j in range(0, len(matrix[0])):
        #     target = matrix[i][j]
        #     while(i <= len(matrix)-1 and j <= len(matrix[0])-1):
        #         if matrix[i][j] != target:
        #             return False
        #         else:
        #             j += 1
        #             i += 1
        #     i = 0
        # j = 0
        # for i in range(1, len(matrix)):
        #     target = matrix[i][j]
        #     while(i <= len(matrix)-1 and j <= len(matrix[0])-1):
        #         if matrix[i][j] != target:
        #             return False
        #         else:
        #             j += 1
        #             i += 1
        #     j = 0
        # return True
        if len(matrix) == 1 or len(matrix[0]) == 1:
            return True
        for i in range(0, len(matrix)-1):
            if matrix[i][:-1] != matrix[i+1][1:]:
                return False
        return True

答案解析:本题注释的部分思路很简单,其实就是分别对比对角线的元素,不相等就返回False。但是后来发现题目指出,如果每次只能调动这个矩阵的部分行该如何做,那就是每次比较每行矩阵除去最后一个元素之后和下一行除去第一个元素是否相等,不等则返回False。

830.较大分组的位置

In a string S of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like S = “abbxxxxzyy” has the groups “a”, “bb”, “xxxx”, “z” and “yy”.

Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.

The final answer should be in lexicographic order.

Example 1:

Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting  3 and ending positions 6.

Example 2:

Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.

Example 3:

Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Note:  1 <= S.length <= 1000

python解答:

class Solution(object):
    def largeGroupPositions(self, S):
        """
        :type S: str
        :rtype: List[List[int]]
        """
        if len(S) == 0 or len(S) == 1:
            return []
        target = S[0]
        count = 1
        list1 = []
        for i in range(1, len(S)):
            if S[i] == target:
                count += 1
            else:
                if count >= 3:
                    list1.append([i-count, i-1])
                count = 1
                target = S[i]
        if count >= 3:
            list1.append([len(S)-count, len(S)-1])
        return list1

答案解析:就是依次查数,大于三个的元素的index返回即可。

832.翻转图像

Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].

To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].

Example 1:

Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]

Example 2:

Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Notes:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1

python解答:

class Solution(object):
    def flipAndInvertImage(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        # m = len(A)
        n = len(A[0])
        # if m == 0 or n == 0:
        #     return A
        # target = [[None for item in range(n)] for i in range(m)]
        # for i in range(m):
        #     for j in range(n):
        #         target[i][j] = 1 - A[i][n-j-1]
        # return target
        for row in A:
            for col in range(0, (n+1)/2):
                row[col], row[-col-1] = 1- row[-col-1], 1-row[col]
        return A

答案解析:本题比较简单,其实就是每一行的元素对称交换之后把各自都取反即可。

840.矩阵中的幻方

A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

Given an grid of integers, how many 3 x 3 “magic square” subgrids are there? (Each subgrid is contiguous).

Example 1:

Input: [[4,3,8,4],
        [9,5,1,9],
        [2,7,6,2]]
Output: 1
Explanation: 
The following subgrid is a 3 x 3 magic square:
438
951
276

while this one is not:
384
519
762

In total, there is only one magic square inside the given grid.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
0 <= grid[i][j] <= 15

python解答:

class Solution(object):
    def numMagicSquaresInside(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid)
        n = len(grid[0])
        target = 0
        def count(a, b, c, d, e, f, g, h, i):
            if sorted([a, b, c, d, e, f, g, h, i]) != range(1, 10):
                return False
            else:
                if a+b+c == d+e+f == g+h+i == a+d+g == b+e+h == c+f+i == a+e+i == c+e+g == 15:
                    return True

        for r in range(m-2):
            for c in range(n-2):
                if grid[r+1][c+1] != 5:
                    continue
                if count(grid[r][c], grid[r][c+1], grid[r][c+2], grid[r+1][c], grid[r+1][c+1], grid[r+1][c+2], grid[r+2][c], grid[r+2][c+1], grid[r+2][c+2]):
                    target += 1
        return target

答案解析:这一题需要仔细阅读题目,其实不复杂,但是需要读出来本题里面的很多隐含条件:因为要求3*3的是1-9不同的数字,所以注定了这9个数字的和为45,而因为每一行都相等,所以每一行都是15,同样地每一列以及两个对角线也都是15。而且,我们把经过中心点的4条线加起来会是60,这里面刚好包含了9个数字以及额外的3个中心点,所以60-45就是中心点的三倍大小,那么这个中心点一定要是5.因此,有了这些条件,代码就比较简单去实现了。

849.到最近的人的最大距离

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return that maximum distance to closest person.

Example 1:

Input: [1,0,0,0,1,0,1]
Output: 2
Explanation: 
If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

Example 2:

Input: [1,0,0,0]
Output: 3
Explanation: 
If Alex sits in the last seat, the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Constraints:
2 <= seats.length <= 20000
seats contains only 0s or 1s, at least one 0, and at least one 1.

python解答:

class Solution(object):
    def maxDistToClosest(self, seats):
        """
        :type seats: List[int]
        :rtype: int
        """
        # list1 = []
        # target = -1
        # for i in range(len(seats)):
        #     if seats[i] == 1:
        #         list1.append(i)
        # if len(list1) == 1:
        #     return max(len(seats) - 1 - list1[0], list1[0])
        # for i in range(len(list1)-1):
        #     inter = (list1[i+1] + list1[i] + 1) // 2
        #     min_interval = min(list1[i+1]-inter, inter-list1[i])
        #     target = max(target, min_interval)
        # return max(target, list1[0], len(seats) - 1 - list1[-1])
        count = 0
        target = -1
        pre, back = -1, -1
        for i in range(len(seats)):
            if seats[i] != 1:
                count += 1
            else:
                if pre < 0:
                    pre = i
                back = i
                target = max(target, (count + 1) // 2)
                count = 0
        return max(target, pre, len(seats) - 1 - back)

答案解析:本题不是特别复杂,其实就是比较两个1之间的0的个数,取这些0个数的中间数,最后再和第一个1前面和最后一个1后面的0的个数比较一下,取最大值即可。

867.转置矩阵

Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it’s main diagonal, switching the row and column indices of the matrix.
在这里插入图片描述
Example 1:

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

Example 2:

Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Note:
1 <= A.length <= 1000
1 <= A[0].length <= 1000

python解答:

class Solution(object):
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        # target = []
        # for j in range(len(A[0])):
        #     list1 = []
        #     for i in range(len(A)):
        #         list1.append(A[i][j])
        #     target.append(list1)
        # return target
        return [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))]

答案解析:本题比较简单,尤其是评论给的这一种一行代码,十分简洁。

888.公平的糖果交换

Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has.

Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (The total amount of candy a person has is the sum of the sizes of candy bars they have.)

Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange.

If there are multiple answers, you may return any one of them. It is guaranteed an answer exists.

Example 1:

Input: A = [1,1], B = [2,2]
Output: [1,2]

Example 2:

Input: A = [1,2], B = [2,3]
Output: [1,2]

Example 3:

Input: A = [2], B = [1,3]
Output: [2,3]

Example 4:

Input: A = [1,2,5], B = [2,4]
Output: [5,4]
Note:
1 <= A.length <= 10000
1 <= B.length <= 10000
1 <= A[i] <= 100000
1 <= B[i] <= 100000
It is guaranteed that Alice and Bob have different total amounts of candy.
It is guaranteed there exists an answer.

python解答:

class Solution(object):
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        sum_A = sum(A)
        sum_B = sum(B)
        set_B = set(B)
        sum_mean = (sum_A + sum_B) // 2
        for item in A:
            if (item + sum_mean - sum_A) in set_B:
                return [item, item + sum_mean - sum_A]

答案解析:本题需要确定两个糖果之和平均值就是交换之后应有的值:(A+B)/2,那么只需要看A中的哪个元素加上A原元素之和和平均值的差值,在B中存在即可,最后返回这两个数。

896.单调数列

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].

Return true if and only if the given array A is monotonic.

Example 1:

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

Example 2:

Input: [6,5,4,4]
Output: true

Example 3:

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

Example 4:

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

Example 5:

Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000

python解答:

class Solution(object):
    def isMonotonic(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        # B = deepcopy(A)
        # C = deepcopy(A)
        # A.sort()
        # B.sort(reverse=True)
        # if C == A or C == B:
        #     return True
        # else:
        #     return False
        if len(A) == 0 or len(A) == 1:
            return True
        if A[-1] >= A[0]:
            for i in range(0, len(A)-1):
                if A[i+1] < A[i]:
                    return False
        else:
            for i in range(0, len(A)-1):
                if A[i+1] > A[i]:
                    return False
        return True

答案解析:本题根据最后一个元素是否大于第一个元素来判断他是升序还是降序,接下来一个个比较即可。

905.按奇偶排序数组

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000

python解答:

class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        a = len(A)
        target = [None for i in range(a)]
        odd_index = a-1
        even_index = 0
        for i in range(a):
            if A[i] % 2 == 0:
                target[even_index] = A[i]
                even_index += 1
            else:
                target[odd_index] = A[i]
                odd_index -= 1
        return target

答案解析:本题其实就是维护两个指针,分别指向奇数和偶数部分。

914.卡牌分组

In a deck of cards, each card has an integer written on it.

Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

Each group has exactly X cards.
All the cards in each group have the same integer.

Example 1:

Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Example 2:

Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.

Example 3:

Input: deck = [1]
Output: false
Explanation: No possible partition.

Example 4:

Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].

Example 5:

Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].
Constraints:
1 <= deck.length <= 10^4
0 <= deck[i] < 10^4

python解答:

class Solution(object):
    def hasGroupsSizeX(self, deck):
        """
        :type deck: List[int]
        :rtype: bool
        """
        if len(deck) == 1:
            return False
        dict1 = {}
        for item in deck:
            if item in dict1:
                dict1[item] += 1
            else:
                dict1[item] = 1
        list1 = []
        for item in dict1:
            list1.append(dict1[item])
        if len(list1) == 1:
            return True
        def gcd(x, y):
            if x%y == 0:
                return y
            else:
                return gcd(y, x%y)
        g = -1
        for i in range(len(list1)):
            if i == 0:
                g = list1[0]
            else:
                g = gcd(g, list1[i])
        if g <= 1:
            return False
        return True

答案解析:本题关键在于求最大公约数,在这里我简单推导了一下:
假如输入a,b,那么我们可以列方程式: x 1 b + m 1 = a x_{1}b+m_{1}=a x1b+m1=a, 如果 m 1 = 0 m_{1}=0 m1=0,那么我们可以说b是最大公约数,否则,我们将 b , m 1 b,m_{1} b,m1输入,那么 x 2 m 1 + m 2 = b x_{2}m_{1}+m_{2}=b x2m1+m2=b,如果 m 2 = 0 m_{2}=0 m2=0,那么 m 1 m_{1} m1此时是最大公约数,因为原式可以化简为 x 1 x 2 m 1 + m 1 = a x_{1}x_{2}m_{1}+m_{1}=a x1x2m1+m1=a,其中 x 1 x 2 x_{1}x_{2} x1x2是整数。那么依次类推,直到第n次,最后 m n m_{n} mn为0,那么 m n − 1 m_{n-1} mn1就是最大公约数。

922.按奇偶排序数组2

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000

python解答:

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        # target = [None for i in range(len(A))]
        # even, odd = 0, 1
        # for item in A:
        #     if item % 2 == 0:
        #         target[even] = item
        #         even += 2
        #     else:
        #         target[odd] = item
        #         odd += 2
        # return target
        j = 1
        for i in range(0, len(A), 2):
            if A[i] % 2 == 1:
                while A[j] % 2 == 1:
                    j += 2
                # even = A[j]
                # A[j] = A[i]
                # A[i] = even
                A[i], A[j] = A[j], A[i]
        return A

答案解析:本题主要思路是:当偶数index处的元素没问题的时候,奇数处元素也没问题,那么只需要把偶数index中odd和附近在奇数index中的even交换一下即可。

941.有效的山脉数组

Given an array A of integers, return true if and only if it is a valid mountain array.

Recall that A is a mountain array if and only if:

A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < … A[i-1] < A[i]
A[i] > A[i+1] > … > A[A.length - 1]

Example 1:

Input: [2,1]
Output: false

Example 2:

Input: [3,5,5]
Output: false

Example 3:

Input: [0,3,2,1]
Output: true
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000 

python解答:

class Solution(object):
    def validMountainArray(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        if len(A) < 3:
            return False
        # index = -1
        # count = 0 
        # target = max(A)
        # for i in range(len(A)):
        #     if A[i] == target:
        #         index = i
        #         count += 1
        #     if count > 1 or index == 0 or index == len(A)-1:
        #         return False
        # if index < 0:
        #     return False
        # for i in range(index):
        #     if A[i] >= A[i+1]:
        #         return False
        # for i in range(index+1, len(A)-1):
        #     if A[i] <= A[i+1]:
        #         return False
        # return True
        N = len(A)
        i = 0
        while i < N-1 and A[i] < A[i+1]:
            i += 1
        if i == 0 or i == N-1:
            return False
        while i < N-1 and A[i] > A[i+1]:
            i += 1
        if i != N -1:
            return False
        return True

答案解析:本题首先依次比较前后元素,直到前面的元素大于或等于后一个元素,则说明到最高峰了,然后再比较这个元素后面的是否依次下降,如果是的话,则返回True。

977.有序数组的平方

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.

python解答:

class Solution(object):
    def sortedSquares(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        for i in range(len(A)):
            A[i] *= A[i]
        A.sort()
        return A

答案解析:本题比较简单,就是平方后排序。

985.查询后的偶数和

We have an array A of integers, and an array queries of queries.

For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index]. Then, the answer to the i-th query is the sum of the even values of A.

(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query.

Example 1:

Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation: 
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length

python解答:

class Solution(object):
    def sumEvenAfterQueries(self, A, queries):
        """
        :type A: List[int]
        :type queries: List[List[int]]
        :rtype: List[int]
        """
        even_sum = 0
        for item in A:
            if item % 2 == 0:
                even_sum += item
        target = []
        for i, j in queries:
            if A[j] % 2 == 0:
                even_sum -= A[j]
            A[j] += i
            if A[j] % 2 == 0:
                even_sum += A[j]
            target.append(even_sum)
        return target

答案解析:本题主要是首先判别,查询的数字是否为偶数,如果是,则先在总和里减去原数字,然后判断变化后的数字是否为偶数,如果为偶数,则加上去。

989.数组形式的整数加法

For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].

Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.

Example 1:

Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:

Input: A = [2,7,4], K = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:

Input: A = [2,1,5], K = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

Example 4:

Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
Output: [1,0,0,0,0,0,0,0,0,0,0]
Explanation: 9999999999 + 1 = 10000000000
Note:
1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
If A.length > 1, then A[0] != 0

python解答:

class Solution(object):
    def addToArrayForm(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: List[int]
        """
        A[-1] += K
        for i in xrange(len(A) - 1, -1, -1):
            carry, A[i] = divmod(A[i], 10)
            if i: 
                A[i-1] += carry
        if carry:
            A = list(map(int, str(carry))) + A
        return A

答案解析:本题采用的先把数字加到最后一个元素,然后依次把%10的数留下,并将剩余的数加到前一位数中,最后直到第一位数,并且如果第一位数大于10,则直接转化为list,和原list合并。

999.可以被一步捕获的棋子数

On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters ‘R’, ‘.’, ‘B’, and ‘p’ respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.

The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.

Return the number of pawns the rook can capture in one move.

Example 1:
在这里插入图片描述

Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation: 
In this example the rook is able to capture all the pawns.

Example 2:
在这里插入图片描述

Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation: 
Bishops are blocking the rook to capture any pawn.

Example 3:
在这里插入图片描述

Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation: 
The rook can capture the pawns at positions b5, d6 and f5.
Note:
board.length == board[i].length == 8
board[i][j] is either 'R', '.', 'B', or 'p'
There is exactly one cell with board[i][j] == 'R'

python解答:

class Solution(object):
    def numRookCaptures(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        rx, ry = 0, 0
        for i in range(8):
            for j in range(8):
                if board[i][j] == 'R':
                    rx = i
                    ry = j
        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
        count = 0
        for i in range(4):
            step = 1
            while True:
                nx = rx + step*dx[i]
                ny = ry + step*dy[i]
                if nx < 0 or nx > 7 or ny < 0 or ny > 7 or board[nx][ny] == 'B':
                    break
                if board[nx][ny] == 'p':
                    count += 1
                    break
                step += 1
        return count

答案解析:本题就是按照四个方向,依次遍历。但是,官方给出了方向数组,就提供了极大的便利,否则可能需要使用四个for循环,依次来走完四个方向,主要好处是代码简洁。

1002.查找常用字符

Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

You may return the answer in any order.

Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter

python解答:

class Solution(object):
    def commonChars(self, A):
        """
        :type A: List[str]
        :rtype: List[str]
        """
        list1 = []
        for item in set(A[0]):
            count = min([a.count(item) for a in A])
            ele = count * item
            for i in ele:
                list1.append(i)
        return list1

答案解析:本题的思想是直接利用A中的第一个字符串中的字母,来分别计算每个字符串中出现这些字母的次数,最小会是0,也就是没有出现这些字母,最后存入list1中并返回即可。

1010.总持续时间可被60整除的歌曲

In a list of songs, the i-th song has a duration of time[i] seconds.

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

Example 1:

Input: [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60

Example 2:

Input: [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.
Note:
1 <= time.length <= 60000
1 <= time[i] <= 500

python解答:

class Solution(object):
    def numPairsDivisibleBy60(self, time):
        """
        :type time: List[int]
        :rtype: int
        """
        count = 0
        if len(time) == 1:
            return 0
        dict1 = {}
        for i in range(len(time)):
            time[i] %= 60
            if time[i] in dict1:
                dict1[time[i]] += 1
            else:
                dict1[time[i]] = 1
        for i in range(31):
            if i in [0, 30]:
                if i in dict1 and dict1[i] > 1:
                    count += dict1[i] * (dict1[i] - 1) / 2
            else:
                if i in dict1 and (60-i) in dict1:
                    count += dict1[i] * dict1[60-i]
        return count

答案解析:本题如果遍历的话,会超时。实际上,每个数除以60的余数可以被用来判断,如果两个数的余数相加刚好为0或者60,那么可以凑成一对,本题的思路也是基于此来做的。

1013.将数组分成和相等的三个部分

Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.

Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + … + A[i] == A[i+1] + A[i+2] + … + A[j-1] == A[j] + A[j-1] + … + A[A.length - 1])

Example 1:

Input: A = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:

Input: A = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:

Input: A = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4

python解答:

class Solution(object):
    def canThreePartsEqualSum(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        if sum(A) % 3 != 0:
            return False
        each = sum(A)/3
        total = 0
        first = False
        for item in A[:-1]:
            total += item
            if not first and total == each:
                first = True
                total = 0
            elif first and total == each:
                return True
        return False

答案解析:本题思路较为简单,只需要求出数组和,之后除以3,就对应三部分的和,如果存在第一个部分和第二部分的和是总和/3,那么剩下那一部分的和一定也是总和/3。

1018.可被5整除的二进制前缀

Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.)

Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5.

Example 1:

Input: [0,1,1]
Output: [true,false,false]
Explanation: 
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.  Only the first number is divisible by 5, so answer[0] is true.

Example 2:

Input: [1,1,1]
Output: [false,false,false]

Example 3:

Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]

Example 4:

Input: [1,1,1,0,1]
Output: [false,false,false,false,false]
Note:
1 <= A.length <= 30000
A[i] is 0 or 1

python解答:

class Solution(object):
    def prefixesDivBy5(self, A):
        """
        :type A: List[int]
        :rtype: List[bool]
        """
        list1 = []
        for i in range(len(A)):
            if i:
                A[i] = (A[i] + A[i-1]*2) % 5
            if A[i] == 0:
                list1.append(True)
            else:
                list1.append(False)
        return list1

答案解析:本题使用动态规划,依次把前面的元素求和,之后乘2,相当于全部左移一位,最后加上当前位置的元素。并且,为了防止溢出,将元素对5求余,如果余数为0,那么说明可以整除,返回一个True。

1051.高度检查器

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

Example 1:

Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation: 
Current array : [1,1,4,2,1,3]
Target array  : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.

Example 2:

Input: heights = [5,1,2,3,4]
Output: 5

Example 3:

Input: heights = [1,2,3,4,5]
Output: 0
Constraints:
1 <= heights.length <= 100
1 <= heights[i] <= 100

python解答:

class Solution(object):
    def heightChecker(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        # target = heights[:]
        # heights.sort()
        # count = 0
        # for i in range(len(heights)):
        #     if heights[i] != target[i]:
        #         count += 1
        # return count
        count = 0
        list1 = [0] * 101
        for i in heights:
            list1[i] += 1
        i = 1
        j = 0
        for i in range(1, 101):
            while list1[i] > 0:
                if heights[j] != i:
                    count += 1
                j += 1
                list1[i] -= 1
        return count

答案解析:本题比较简单的思路就是直接排序,然后比较排序后的数组和原数组的元素变化。但是实际上,没有必要去排序,可以记录每个元素出现的次数,然后在它该出现的位置,如果不是这个元素,说明这里的元素需要调动,那么计算器加一。

1089.复写零

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written.

Do the above modifications to the input array in place, do not return anything from your function.

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]
Note:
1 <= arr.length <= 10000
0 <= arr[i] <= 9

python解答:

class Solution(object):
    def duplicateZeros(self, arr):
        """
        :type arr: List[int]
        :rtype: None Do not return anything, modify arr in-place instead.
        """
        target = arr[:]
        i = 0
        j = 0
        while i < len(arr):
            if target[j] != 0:
                arr[i] = target[j]
                i += 1
            else:
                if i != len(arr)-1:
                    arr[i+1] = 0
                arr[i] = 0
                # arr[i+1] = 0
                i += 2
            j += 1

答案解析:本题我采用了一个额外的数组,而官方则是没有借用额外的空间,首先看有几个0会被复制,然后倒序编写数组的元素。

1122.数组的相对排序

Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don’t appear in arr2 should be placed at the end of arr1 in ascending order.

Example 1:

Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Constraints:
arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
Each arr2[i] is distinct.
Each arr2[i] is in arr1.

python解答:

class Solution(object):
    def relativeSortArray(self, arr1, arr2):
        """
        :type arr1: List[int]
        :type arr2: List[int]
        :rtype: List[int]
        """
        target = []
        list1 = []
        dict1 = {}
        for item in arr1:
            if item in arr2 and item in dict1:
                dict1[item] += 1
            elif item in arr2 and item not in dict1:
                dict1[item] = 1
            elif item not in arr2:
                list1.append(item)
        list1.sort()
        for item in arr2:
            for i in range(dict1[item]):
                target.append(item)
        target += list1
        return target

答案解析:本题就是使用一个计数排序,思路比较简单。

1128.等价多米诺骨牌对的数量

Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (ac and bd), or (ad and bc) - that is, one domino can be rotated to be equal to another domino.

Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].

Example 1:

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

1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9

python解答:

class Solution(object):
    def numEquivDominoPairs(self, dominoes):
        """
        :type dominoes: List[List[int]]
        :rtype: int
        """
        for i in range(len(dominoes)):
            dominoes[i].sort()
        count = 0
        dict1 = {}
        for item in dominoes:
            m = str(item[0]) + str(item[1])
            if m in dict1:
                dict1[m] += 1
            else:
                dict1[m] = 1
        for item in dict1.values():
            count += item*(item-1)/2
        return count

答案解析:本题采用计数的方法,例如[1,2]和[2,1]都看作为12,只需要记录出现的次数,然后使用x*(x-1)/2求各个元素对出现的次数,最后相加即可。

1160.拼写单词

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Note:

1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only.

python解答:

class Solution(object):
    def countCharacters(self, words, chars):
        """
        :type words: List[str]
        :type chars: str
        :rtype: int
        """
        chars_ct =Counter(chars)
        count = 0 
        for item in words:
            symbol = True
            words_ct = Counter(item)
            for i in item:
                if chars_ct[i] < words_ct[i]:
                    symbol = False
            if symbol:
                count += len(item)
        return count

答案解析:本题题意其实是只要chars满足某个单词即可,所以只需要看每个单词出现的次数和chars单词的数量相比结果即可。

1170.比较字符串最小字母出现频次

Let’s define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = “dcce” then f(s) = 2 because the smallest character is “c” and its frequency is 2.

Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words.

Example 1:

Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").

Example 2:

Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
Constraints:
1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j], words[i][j] are English lowercase letters.

python解答:

class Solution(object):
    def numSmallerByFrequency(self, queries, words):
        """
        :type queries: List[str]
        :type words: List[str]
        :rtype: L
        """
        for i in range(len(queries)):
            count = 0
            target = min(queries[i])
            for item in queries[i]:
                if item == target:
                    count += 1
            queries[i] = count
        for i in range(len(words)):
            count = 0
            target = min(words[i])
            for item in words[i]:
                if item == target:
                    count += 1
            words[i] = count
        target = []
        count = 0
        for item1 in queries:
            for item2 in words:
                if item1 < item2:
                    count += 1
            target.append(count)
            count = 0
        return target

答案解析:本题是首选计算最小单词出现的次数,然后比较queries中每个元素比words中小的次数即可。

1184.公交站间的距离

A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.

The bus goes along both directions i.e. clockwise and counterclockwise.

Return the shortest distance between the given start and destination stops.

Example 1:

在这里插入图片描述

Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.

Example 2:

在这里插入图片描述

Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.

Example 3:

在这里插入图片描述

Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4

python解答:

class Solution(object):
    def distanceBetweenBusStops(self, distance, start, destination):
        """
        :type distance: List[int]
        :type start: int
        :type destination: int
        :rtype: int
        """
        if start < destination:
            sum1 = sum(distance[start:destination])
            sum2 = sum(distance[destination:]) + sum(distance[:start])
        else:
            sum1 = sum(distance[destination:start])
            sum2 = sum(distance[start:]) + sum(distance[:destination])
        return min(sum1,sum2)

答案解析:本题其实只需要判断des-start之间的距离,以及反向环形距离,返回最小值即可。

1200.最小绝对差

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr

Example 1:

Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

Example 2:

Input: arr = [1,3,6,10,15]
Output: [[1,3]]

Example 3:

Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
Constraints:

2 <= arr.length <= 10^6
-10^6 <= arr[i] <= 10^6

python解答:

class Solution(object):
    def minimumAbsDifference(self, arr):
        """
        :type arr: List[int]
        :rtype: List[List[int]]
        """
        # arr.sort()
        # target = 10^6
        # for i in range(0, len(arr)-1):
        #     target = min(target, arr[i+1]-arr[i])
        # list1 = []
        # for i in range(len(arr)-1):
        #     if arr[i]+target == arr[i+1]:
        #         list1.append([arr[i], arr[i+1]])
        # return list1
        arr.sort()
        target = {}
        min_target = arr[1] - arr[0]
        for i in range(len(arr)-1):
            diff = arr[i+1] - arr[i]
            if diff <= min_target:
                if diff in target:
                    target[diff].append([arr[i], arr[i+1]])
                else:
                    target[diff] = [[arr[i], arr[i+1]]]
                min_target = diff
        return target[min_target]

答案解析:本题首选还是先排序,那么最小绝对差就一定在i+1和i之间,只需要找到最小绝对差,并且相邻两个元素绝对差等于最小绝对差,返回对应的集合即可。

1217.玩筹码

We have n chips, where the position of the ith chip is position[i].

We need to move all the chips to the same position, In one step, we can change the position of the ith chip from position[i] to:

position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return the minimum cost needed to move all the chips to the same position.

Example 1:
在这里插入图片描述

Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.

Example 2:
在这里插入图片描述

Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at poistion 3 to position 2. Each move has cost = 1. The total cost = 2.

Example 3:

Input: position = [1,1000000000]
Output: 1
Constraints:

1 <= position.length <= 100
1 <= position[i] <= 10^9

python解答:

class Solution(object):
    def minCostToMoveChips(self, position):
        """
        :type position: List[int]
        :rtype: int
        """
        odd = 0
        even = 0
        for item in position:
            if item % 2 == 0:
                even += 1
            else:
                odd += 1
        return min(odd, even)

答案解析:本题主要是思路不是很容易想,首先既然跳两格就消耗0,也就是奇数位的都跳到一个奇数位总消耗为0,偶数位的都跳到一个偶数位总消耗为0,最后要么把奇数位的元素都挪到偶数位,或者把偶数位的元素都挪到奇数位,其实最后只需要比较奇数和偶数最小值返回即可。

1232.缀点成线

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

Example 1:

在这里插入图片描述

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:
在这里插入图片描述

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.

python解答:

class Solution(object):
    def checkStraightLine(self, coordinates):
        """
        :type coordinates: List[List[int]]
        :rtype: bool
        """
        # if len(coordinates) == 1:
        #     return True
        # if (coordinates[1][0] - coordinates[0][0]) == 0:
        #     for item in coordinates:
        #         if item[0] != coordinates[0][0]:
        #             return False
        # elif (coordinates[1][1] - coordinates[0][1]) == 0:
        #     for item in coordinates:
        #         if item[1] != coordinates[0][1]:
        #             return False
        # else:
        #     slope = (coordinates[1][1] - coordinates[0][1])/(coordinates[1][0] - coordinates[0][0])
        #     for i in range(1, len(coordinates)-1):
        #         if (coordinates[i+1][0] - coordinates[i][0]) == 0:
        #             return False
        #         if (coordinates[i+1][1] - coordinates[i][1])/(coordinates[i+1][0] - coordinates[i][0]) != slope:
        #             return False
        # return True
        if len(coordinates) == 2:
             return True
        x1, y1 = coordinates[0][0], coordinates[0][1]
        x2, y2 = coordinates[1][0], coordinates[1][1]
        for i in range(2, len(coordinates)):
            x3, y3 = coordinates[i][0], coordinates[i][1]
            if (y3 - y2)*(x2 - x1) != (y2 - y1)*(x3 - x2):
                return False
        return True

答案解析:本题没什么难点,唯一注意的就是能用乘法就不用除法,因为会有很多分母为0的情况需要考虑。

1252.奇数值单元格的数目

Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

Return the number of cells with odd values in the matrix after applying the increment to all indices.

Example 1:
在这里插入图片描述

Input: n = 2, m = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.

Example 2:
在这里插入图片描述

Input: n = 2, m = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.
Constraints:

1 <= n <= 50
1 <= m <= 50
1 <= indices.length <= 100
0 <= indices[i][0] < n
0 <= indices[i][1] < m

python解答:

class Solution(object):
    def oddCells(self, n, m, indices):
        """
        :type n: int
        :type m: int
        :type indices: List[List[int]]
        :rtype: int
        """
        # list1 = [[0] * m for i in range(n)]
        # for i in range(len(indices)):
        #     for j in range(len(list1[0])):
        #         row = indices[i][0]
        #         list1[row][j] += 1
        #     for k in range(len(list1)):
        #         col = indices[i][1]
        #         list1[k][col] += 1
        # count = 0
        # for item in list1:
        #     for ele in item:
        #         if ele % 2 != 0:
        #             count += 1
        # return count
        rows = [False] * n
        cols = [False] * m
        for r,c in indices:
            rows[r] = not rows[r]
            cols[c] = not cols[c]
        count = 0
        for r in range(n):
            for c in range(m):
                if rows[r] != cols[c]:
                    count += 1
        return count

答案解析:本题使用暴力解法即可,但是也有一些简便方法,因为并不要求构造出这个矩阵,其实从0开始,只需要看某个位置加的次数是否为奇数即可。

1260.二维网格迁移

Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.

Example 1:
在这里插入图片描述

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]

Example 2:
在这里插入图片描述

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:

m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100

python解答:

class Solution(object):
    def shiftGrid(self, grid, k):
        """
        :type grid: List[List[int]]
        :type k: int
        :rtype: List[List[int]]
        """
        target = [[0] * len(grid[0]) for _ in range(len(grid))]
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                new_col = (j + k) % len(grid[0])
                add_count = (j + k) // len(grid[0])
                new_row = (i + add_count) % len(grid)
                target[new_row][new_col] = grid[i][j]
        return target

答案解析:本题主要就是通过求模计算,来分别算出每个元素移动的次数。

1266.访问所有点的最小时间

On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points.

You can move according to the next rules:

In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second).
You have to visit the points in the same order as they appear in the array.

Example 1:
s

Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]   
Time from [1,1] to [3,4] = 3 seconds 
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds

Example 2:

Input: points = [[3,2],[-2,2]]
Output: 5

Constraints:

points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000

python解答:

class Solution(object):
    def minTimeToVisitAllPoints(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        count = 0
        for i in range(len(points)-1):
            y = abs(points[i+1][1] - points[i][1])
            x = abs(points[i+1][0] - points[i][0])
            count += max(x,y)
        return count

答案解析:本题就是使用切尔比夫距离。

1275.找出井字棋的获胜者

Tic-tac-toe is played by two players A and B on a 3 x 3 grid.

Here are the rules of Tic-Tac-Toe:

Players take turns placing characters into empty squares (" ").
The first player A always places “X” characters, while the second player B always places “O” characters.
“X” and “O” characters are always placed into empty squares, never on filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play.

Return the winner of the game if it exists (A or B), in case the game ends in a draw return “Draw”, if there are still movements to play return “Pending”.

You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.

Example 1:

Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X  "    "X  "    "X  "    "X  "    "X  "
"   " -> "   " -> " X " -> " X " -> " X "
"   "    "O  "    "O  "    "OO "    "OOX"

Example 2:

Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X  "    "X  "    "XX "    "XXO"    "XXO"    "XXO"
"   " -> " O " -> " O " -> " O " -> "XO " -> "XO " 
"   "    "   "    "   "    "   "    "   "    "O  "

Example 3:

Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"

Example 4:

Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X  "
" O "
"   "

Constraints:

1 <= moves.length <= 9
moves[i].length == 2
0 <= moves[i][j] <= 2
There are no repeated elements on moves.
moves follow the rules of tic tac toe.

python解答:

class Solution(object):
    def tictactoe(self, moves):
        """
        :type moves: List[List[int]]
        :rtype: str
        """
        if len(moves) == 1 or len(moves) == 2:
            return "Pending"
        count = [0] * 8
        # count[0]~count[2] 1~3行
        # count[3]~count[5] 1~3列
        # count[6] 正对角线
        # count[7] 负对角线
        for i in range(len(moves)-1, -1, -2):
            count[moves[i][0]] += 1
            count[moves[i][1] + 3] += 1
            if moves[i][0] == moves[i][1]:
                count[6] += 1
            if (moves[i][0] + moves[i][1]) == 2:
                count[7] += 1
            if (count[moves[i][0]] == 3 or count[moves[i][1] +3] == 3 or count[6] == 3 or count[7] == 3):
                if len(moves) % 2 == 0:
                    return "B"
                else:
                    return "A"
        if len(moves) == 9:
            return "Draw"
        else:
            return "Pending"

答案解析:官方给出的就是直接列举出可能出现的结果,但是如果不是在3*3的棋盘上就会出现问题,因此使用一个list来分别存储每一行、列和对角线出现重复元素的次数,当出现三次即可返回。

1287.有序数组中出现次数超过25%的元素

Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time.

Return that integer.

Example 1:

Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:

1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5

python解答:

class Solution(object):
    def findSpecialInteger(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        length = 0.25 * len(arr)
        dict1 = {}
        for item in arr:
            if item in dict1:
                dict1[item] += 1
            else:
                dict1[item] = 1
            if dict1[item] > length:
                return item

1295.统计位数为偶数的数字

Given an array nums of integers, return how many of them contain an even number of digits.

Example 1:

Input: nums = [12,345,2,6,7896]
Output: 2
Explanation: 
12 contains 2 digits (even number of digits). 
345 contains 3 digits (odd number of digits). 
2 contains 1 digit (odd number of digits). 
6 contains 1 digit (odd number of digits). 
7896 contains 4 digits (even number of digits). 
Therefore only 12 and 7896 contain an even number of digits.

Example 2:

Input: nums = [555,901,482,1771]
Output: 1 
Explanation: 
Only 1771 contains an even number of digits.
Constraints:

1 <= nums.length <= 500
1 <= nums[i] <= 10^5

python解答:

class Solution(object):
    def findNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        target = 0
        for item in nums:
            if len(str(item)) % 2 == 0:
                target += 1
        return target

1299.将每个元素替换为右侧最大元素

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Example 1:

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:

1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5

python解答:

class Solution(object):
    def replaceElements(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        if len(arr) == 1:
            return [-1]
        target = [0] * len(arr)
        max_target = 0
        target[-1] = -1
        for i in range(len(arr)-1, 0, -1):
            max_target = max(max_target, arr[i])
            target[i-1] = max_target
        return target

1304.和为零的N个唯一整数

Given an integer n, return any array containing n unique integers such that they add up to 0.

Example 1:

Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2:

Input: n = 3
Output: [-1,0,1]

Example 3:

Input: n = 1
Output: [0]
Constraints:

1 <= n <= 1000

python解答:

class Solution(object):
    def sumZero(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        if n == 1:
            return [0]
        elif n == 2:
            return [-1, 1]
        else:
            target = [x for x in range(n-1)]
            target.append(-sum(target))
            return target

1313.解压缩编码列表

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [freq, val] = [nums[2i], nums[2i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.

Return the decompressed list.

Example 1:

Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].

Example 2:

Input: nums = [1,1,2,3]
Output: [1,3,3]
Constraints:

2 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100

python解答:

class Solution(object):
    def decompressRLElist(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        target = []
        for i in range(0, len(nums), 2):
            for j in range(nums[i]):
                target.append(nums[i+1])
        return target

1331.数组序号转换

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

Rank is an integer starting from 1.
The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.

Example 1:

Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

Example 2:

Input: arr = [100,100,100]
Output: [1,1,1]
Explanation: Same elements share the same rank.

Example 3:

Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]
Constraints:

0 <= arr.length <= 105
-109 <= arr[i] <= 109

python解答:

class Solution(object):
    def arrayRankTransform(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        a = sorted(set(arr))
        dict1 = {}
        i = 1
        for item in a:
            dict1[item] = i
            i += 1
        target = []
        for item in arr:
            target.append(dict1[item])
        return target

答案解析:这里面需要去重,可以有效地提升效率。

1337.方阵中战斗力最弱的k行

Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest.

A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros.

Example 1:

Input: mat = 
[[1,1,0,0,0],
 [1,1,1,1,0],
 [1,0,0,0,0],
 [1,1,0,0,0],
 [1,1,1,1,1]], 
k = 3
Output: [2,0,3]
Explanation: 
The number of soldiers for each row is: 
row 0 -> 2 
row 1 -> 4 
row 2 -> 1 
row 3 -> 2 
row 4 -> 5 
Rows ordered from the weakest to the strongest are [2,0,3,1,4]

Example 2:

Input: mat = 
[[1,0,0,0],
 [1,1,1,1],
 [1,0,0,0],
 [1,0,0,0]], 
k = 2
Output: [0,2]
Explanation: 
The number of soldiers for each row is: 
row 0 -> 1 
row 1 -> 4 
row 2 -> 1 
row 3 -> 1 
Rows ordered from the weakest to the strongest are [0,2,3,1]
Constraints:

m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j] is either 0 or 1.

python解答:

class Solution(object):
    def kWeakestRows(self, mat, k):
        """
        :type mat: List[List[int]]
        :type k: int
        :rtype: List[int]
        """
        # length = len(mat)
        # arr = []
        # for item in mat:
        #     arr.append(sum(item))
        # index = [i for i in range(length)]
        # index.sort(key=lambda i : (arr[i], i))
        # return index[:k]
        arr = []
        for i, value in enumerate(mat):
            arr.append((sum(value), i))
        arr.sort()
        target = []
        for item in range(k):
            target.append(arr[item][1])
        return target

1346.检查整数及其两倍数是否存在

Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).

More formally check if there exists two indices i and j such that :

i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

Example 1:

Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.

Example 2:

Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.

Example 3:

Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.
Constraints:

2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3

python解答:

class Solution(object):
    def checkIfExist(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        dict1 = {}
        for item in arr:
            if item not in dict1:
                dict1[item] = 1
            else:
                dict1[item] += 1
        for item in arr:
            if 2*item in dict1:
                if item != 0:
                    return True
                else:
                    if dict1[0] >= 2:
                        return True
        return False

1351.统计有序矩阵中的负数

Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.

Return the number of negative numbers in grid.

Example 1:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.

Example 2:

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

Example 3:

Input: grid = [[1,-1],[-1,-1]]
Output: 3

Example 4:

Input: grid = [[-1]]
Output: 1
Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100

python解答:

class Solution(object):
    def countNegatives(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        target = 0
        col = len(grid[0])
        row = len(grid)
        for i in range(col-1, -1, -1):
            for j in range(0, row):
                if grid[j][i] < 0:
                    target += (row - j)
                    break
        return target

1365.有多少小于当前数字的数字

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j’s such that j != i and nums[j] < nums[i].

Return the answer in an array.

Example 1:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation: 
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1). 
For nums[3]=2 there exist one smaller number than it (1). 
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

Example 2:

Input: nums = [6,5,4,8]
Output: [2,1,0,3]

Example 3:

Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:

2 <= nums.length <= 500
0 <= nums[i] <= 100

python解答:

class Solution(object):
    def smallerNumbersThanCurrent(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        new = nums[:]
        new.sort()
        dict1 = {}
        i = 0
        for item in new:
            if item not in dict1:
                dict1[item] = i
            i += 1
        target = []
        for item in nums:
            target.append(dict1[item])
        return target 

1380.矩阵中的幸运数

Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

Example 1:

Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column

Example 2:

Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.

Example 3:

Input: matrix = [[7,8],[1,2]]
Output: [7]
Constraints:

m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5.
All elements in the matrix are distinct.

python解答:

class Solution(object):
    def luckyNumbers (self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        row = []
        for item in matrix:
            row.append(min(item))
        target = []
        for j in range(len(matrix[0])):
            col = max([matrix[i][j] for i in range(len(matrix))])
            if col in row:
                target.append(col)
        return target 

答案解析:本题如果先求出每行的最小值,再去看是否是这一列的最大值,就会比较麻烦,其实只需要先求出每行最小值和每列最大值,看是否存在相同的元素即可。

1385.两个数组间的距离值

Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.

The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.

Example 1:

Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation: 
For arr1[0]=4 we have: 
|4-10|=6 > d=2 
|4-9|=5 > d=2 
|4-1|=3 > d=2 
|4-8|=4 > d=2 
For arr1[1]=5 we have: 
|5-10|=5 > d=2 
|5-9|=4 > d=2 
|5-1|=4 > d=2 
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2

Example 2:

Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2

Example 3:

Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
Constraints:

1 <= arr1.length, arr2.length <= 500
-10^3 <= arr1[i], arr2[j] <= 10^3
0 <= d <= 100

python解答:

class Solution(object):
    def findTheDistanceValue(self, arr1, arr2, d):
        """
        :type arr1: List[int]
        :type arr2: List[int]
        :type d: int
        :rtype: int
        """
        count = 0
        for item in arr1:
            symbol = True
            for j in arr2:
                if abs(item - j) <= d:
                    symbol = False
                    break
            if symbol:
                count += 1
        return count

1389.按既定顺序创建目标数组

Given two arrays of integers nums and index. Your task is to create target array under the following rules:

Initially target array is empty.
From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
Repeat the previous step until there are no elements to read in nums and index.
Return the target array.

It is guaranteed that the insertion operations will be valid.

Example 1:

Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums       index     target
0            0        [0]
1            1        [0,1]
2            2        [0,1,2]
3            2        [0,1,3,2]
4            1        [0,4,1,3,2]

Example 2:

Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums       index     target
1            0        [1]
2            1        [1,2]
3            2        [1,2,3]
4            3        [1,2,3,4]
0            0        [0,1,2,3,4]

Example 3:

Input: nums = [1], index = [0]
Output: [1]
Constraints:

1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= I

python解答:

class Solution(object):
    def createTargetArray(self, nums, index):
        """
        :type nums: List[int]
        :type index: List[int]
        :rtype: List[int]
        """
        target = []
        for i in range(len(nums)):
            target.insert(index[i], nums[i])
        return target

1394.找出数组中的幸运数

Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.

Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.

Example 1:

Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.

Example 2:

Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:

Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.

Example 4:

Input: arr = [5]
Output: -1

Example 5:

Input: arr = [7,7,7,7,7,7,7]
Output: 7
Constraints:

1 <= arr.length <= 500
1 <= arr[i] <= 500

python解答:

class Solution(object):
    def findLucky(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        dict1 = {}
        for item in arr:
            if item not in dict1:
                dict1[item] = 1
            else:
                dict1[item] += 1
        # target = []
        # for item in dict1:
        #     if dict1[item] == item:
        #         target.append(item)
        # if len(target) == 0:
        #     return -1
        # else:
        #     return max(target)
        target = -1
        for k, v in dict1.items():
            if k == v and k > target:
                target = k
        return target

1399.统计最大组的数目

Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.

Return how many groups have the largest size.

Example 1:

Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size.

Example 2:

Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.

Example 3:

Input: n = 15
Output: 6

Example 4:

Input: n = 24
Output: 5
Constraints:

1 <= n <= 10^4

python解答:

class Solution(object):
    def countLargestGroup(self, n):
        """
        :type n: int
        :rtype: int
        """
        dict1 = {}
        for i in range(1, n+1):
            ele = sum(int(j) for j in str(i))
            if ele in dict1:
                dict1[ele] += 1
            else:
                dict1[ele] = 1
        large  = max(dict1.values())
        target = 0
        for item in dict1.values():
            if item == large:
                target += 1
        return target

1413.逐步求和得到正数的最小值

Given an array of integers nums, you start with an initial positive value startValue.

In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).

Return the minimum positive value of startValue such that the step by step sum is never less than 1.

Example 1:

Input: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
                step by step sum
                startValue = 4 | startValue = 5 | nums
                  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3
                  (1 +2 ) = 3  | (2 +2 ) = 4    |   2
                  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3
                  (0 +4 ) = 4  | (1 +4 ) = 5    |   4
                  (4 +2 ) = 6  | (5 +2 ) = 7    |   2

Example 2:

Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive. 

Example 3:

Input: nums = [1,-2,-3]
Output: 5
Constraints:

1 <= nums.length <= 100
-100 <= nums[i] <= 100

python解答:

class Solution(object):
    def minStartValue(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        mini = 0
        a_sum = 0
        for item in nums:
            a_sum += item
            if a_sum < mini:
                mini = a_sum
        return 1-mini

1431.拥有最多糖果的孩子

Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.

For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.

Example 1:

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true] 
Explanation: 
Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. 
Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 
Kid 3 has 5 candies and this is already the greatest number of candies among the kids. 
Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. 
Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 

Example 2:

Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false] 
Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy.

Example 3:

Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
Constraints:

2 <= candies.length <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50

python解答:

class Solution(object):
    def kidsWithCandies(self, candies, extraCandies):
        """
        :type candies: List[int]
        :type extraCandies: int
        :rtype: List[bool]
        """
        target = max(candies)
        for i in range(len(candies)):
            if candies[i]+extraCandies >= target:
                candies[i] = True
            else:
                candies[i] = False
        return candies

1450.在既定时间做作业的学生人数

Given two integer arrays startTime and endTime and given an integer queryTime.

The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].

Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.

Example 1:

Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.

Example 2:

Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.

Example 3:

Input: startTime = [4], endTime = [4], queryTime = 5
Output: 0

Example 4:

Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
Output: 0

Example 5:

Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
Output: 5
Constraints:

startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000

python解答:

class Solution(object):
    def busyStudent(self, startTime, endTime, queryTime):
        """
        :type startTime: List[int]
        :type endTime: List[int]
        :type queryTime: int
        :rtype: int
        """
        target = 0
        for i in range(len(startTime)):
            if endTime[i] >= queryTime:
                if startTime[i] <= queryTime:
                    target += 1
        return target

1460.通过翻转子数组使两个数组相等

Given two integer arrays of equal length target and arr.

In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.

Return True if you can make arr equal to target, or False otherwise.

Example 1:

Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.

Example 2:

Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.

Example 3:

Input: target = [1,12], arr = [12,1]
Output: true

Example 4:

Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr doesn't have value 9 and it can never be converted to target.

Example 5:

Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
Output: true
Constraints:

target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000

python解答:

class Solution(object):
    def canBeEqual(self, target, arr):
        """
        :type target: List[int]
        :type arr: List[int]
        :rtype: bool
        """
        target.sort()
        arr.sort()
        if target == arr:
            return True
        else:
            return False

1464.数组中两元素的最大乘积

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

Example 1:

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

Example 2:

Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

Input: nums = [3,7]
Output: 12
Constraints:

2 <= nums.length <= 500
1 <= nums[i] <= 10^3

python解答:

class Solution(object):
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return (nums[-1]-1)*(nums[-2]-1)

1470.重新排列数组

Given the array nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn].

Return the array in the form [x1,y1,x2,y2,…,xn,yn].

Example 1:

Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7] 
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

Example 2:

Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]

Example 3:

Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:

1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3

python解答:

class Solution(object):
    def shuffle(self, nums, n):
        """
        :type nums: List[int]
        :type n: int
        :rtype: List[int]
        """
        # target = []
        # for i in range(n):
        #     target.append(nums[i])
        #     target.append(nums[i+n])
        # return target
        ## 原地交换元素
        for i in range(2*n):
            j = i
            while(nums[i] >= 0):
                if j < n:
                    j = 2*j
                else:
                    j = (j-n)*2 + 1
                nums[i], nums[j] = nums[j], -nums[i]
        for i in range(2*n):
            nums[i] *= -1
        return nums

1475.商品折扣后的最终价格

Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.

Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.

Example 1:

Input: prices = [8,4,6,2,3]
Output: [4,2,4,2,3]
Explanation: 
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. 
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. 
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. 
For items 3 and 4 you will not receive any discount at all.

Example 2:

Input: prices = [1,2,3,4,5]
Output: [1,2,3,4,5]
Explanation: In this case, for all items, you will not receive any discount at all.

Example 3:

Input: prices = [10,1,1,6]
Output: [9,0,1,6]
Constraints:

1 <= prices.length <= 500
1 <= prices[i] <= 10^3

python解答:

class Solution(object):
    def finalPrices(self, prices):
        """
        :type prices: List[int]
        :rtype: List[int]
        """
        stack = []
        for i in range(len(prices)):
            while stack and prices[stack[-1]] >= prices[i]:
                prices[stack[-1]] -= prices[i]
                stack.pop()
            stack.append(i)
        return prices

答案解析:本题主要通过维护一个单调栈来找到每个元素后面第一个小于它的元素。

1480.一维数组的动态和

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

Example 1:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:

Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Constraints:

1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6

python解答:

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

1486.数组异或操作

Given an integer n and an integer start.

Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length.

Return the bitwise XOR of all elements of nums.

Example 1:

Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.

Example 2:

Input: n = 4, start = 3
Output: 8
Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.

Example 3:

Input: n = 1, start = 7
Output: 7

Example 4:

Input: n = 10, start = 5
Output: 2
Constraints:

1 <= n <= 1000
0 <= start <= 1000
n == nums.length

python解答:

class Solution(object):
    def xorOperation(self, n, start):
        """
        :type n: int
        :type start: int
        :rtype: int
        """
        target = 0
        list1 = [start+2*i for i in range(n)]
        for item in list1:
            target ^= item
        return target

1491.去掉最低工资和最高工资后的工资平均值

Given an array of unique integers salary where salary[i] is the salary of the employee i.

Return the average salary of employees excluding the minimum and maximum salary.

Example 1:

Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500

Example 2:

Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000)/1= 2000

Example 3:

Input: salary = [6000,5000,4000,3000,2000,1000]
Output: 3500.00000

Example 4:

Input: salary = [8000,9000,2000,3000,6000,1000]
Output: 4750.00000
Constraints:

3 <= salary.length <= 100
10^3 <= salary[i] <= 10^6
salary[i] is unique.
Answers within 10^-5 of the actual value will be accepted as correct.

python解答:

class Solution(object):
    def average(self, salary):
        """
        :type salary: List[int]
        :rtype: float
        """
        all_sum = sum(salary)
        length = len(salary)
        salary.sort()
        all_sum -= salary[-1]
        all_sum -= salary[0]
        return all_sum/(length - 2.0)

1502.判断能否形成等差数列

Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false.

Example 1:

Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.

Example 2:

Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:

2 <= arr.length <= 1000
-10^6 <= arr[i] <= 10^6

python解答:

class Solution(object):
    def canMakeArithmeticProgression(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        if len(arr) == 2:
            return True
        arr.sort()
        inter = arr[1] - arr[0]
        for i in range(1, len(arr)-1):
            if arr[i+1] - arr[i] != inter:
                return False
        return True

1512.好数对的数目

Given an array of integers nums.

A pair (i,j) is called good if nums[i] == nums[j] and i < j.

Return the number of good pairs.

Example 1:

Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Example 2:

Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.

Example 3:

Input: nums = [1,2,3]
Output: 0
Constraints:

1 <= nums.length <= 100
1 <= nums[i] <= 100

python解答:

class Solution(object):
    def numIdenticalPairs(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dict1 = {}
        for item in nums:
            if item not in dict1:
                dict1[item] = 1
            else:
                dict1[item] += 1
        target = 0
        for item in dict1.values():
            target += item*(item-1)/2
        return target 

1534.统计好三元组

Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.

A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute value of x.

Return the number of good triplets.

Example 1:

Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].

Example 2:

Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
Explanation: No triplet satisfies all conditions.
Constraints:

3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000

python解答:

def countGoodTriplets(self, arr, a, b, c):
        """
        :type arr: List[int]
        :type a: int
        :type b: int
        :type c: int
        :rtype: int
        """
        length = len(arr)
        total = [0] * 1001
        target = 0
        for j in range(length):
            for k in range(j+1, length):
                if abs(arr[j] - arr[k]) <= b:
                    lj, hj = arr[j]-a, arr[j]+a
                    lk, hk = arr[k]-c, arr[k]+c
                    l = max(0, lj, lk)
                    h = min(1000, hj, hk)
                    if l <= h:
                        if l == 0:
                            target += total[h]
                        else:
                            target += total[h] - total[l-1]
            for k in range(arr[j], 1001):
                total[k] += 1
        return target

1539.第k个缺失的正整数

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

Find the kth positive integer that is missing from this array.

Example 1:

Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.

Example 2:

Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:

1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length

python解答:

class Solution(object):
    def findKthPositive(self, arr, k):
        """
        :type arr: List[int]
        :type k: int
        :rtype: int
        """
        target = []
        for i in range(1, arr[0]):
            target.append(i)
        for i in range(len(arr)-1):
            for j in range(arr[i]+1, arr[i+1]):
                target.append(j)
        if k <= len(target):
            return target[k-1]
        else:
            return arr[-1]+(k-len(target))

1550.存在连续三个奇数的数组

Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.

Example 1:

Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.

Example 2:

Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consecutive odds.
Constraints:

1 <= arr.length <= 1000
1 <= arr[i] <= 1000

python解答:

class Solution(object):
    def threeConsecutiveOdds(self, arr):
        """
        :type arr: List[int]
        :rtype: bool
        """
        count = 0
        for item in arr:
            if item % 2 != 0:
                count += 1
                if count == 3:
                    return True
            else:
                count = 0
        return False

1560.圆形赛道上经过次数最多的扇区

Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]

Return an array of the most visited sectors sorted in ascending order.

Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).

Example 1:
在这里插入图片描述

Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.

Example 2:

Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
Output: [2]

Example 3:

Input: n = 7, rounds = [1,3,5,7]
Output: [1,2,3,4,5,6,7]
Constraints:

2 <= n <= 100
1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1] for 0 <= i < m

python解答:

class Solution(object):
    def mostVisited(self, n, rounds):
        """
        :type n: int
        :type rounds: List[int]
        :rtype: List[int]
        """
        start = rounds[0]
        end = rounds[-1]
        if start <= end:
            return list(range(start, end+1))
        else:
            left = list(range(start, n+1))
            right = list(range(1, end+1))
            return right+left

1566.重复至少K次且长度为M的模式

Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.

A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.

Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.

Example 1:

Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.

Example 2:

Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.

Example 3:

Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.

Example 4:

Input: arr = [1,2,3,1,2], m = 2, k = 2
Output: false
Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.

Example 5:

Input: arr = [2,2,2,2], m = 2, k = 3
Output: false
Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.
Constraints:

2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100

python解答:

class Solution(object):
    def containsPattern(self, arr, m, k):
        """
        :type arr: List[int]
        :type m: int
        :type k: int
        :rtype: bool
        """
        i = 0
        while i < len(arr):
            mode = arr[i:i+m]
            if mode*k == arr[i:i+m*k]:
                return True
            i += 1
        return False

1572.矩阵对角线元素的和

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

Example 1:
在这里插入图片描述

Input: mat = [[1,2,3],
              [4,5,6],
              [7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.

Example 2:

Input: mat = [[1,1,1,1],
              [1,1,1,1],
              [1,1,1,1],
              [1,1,1,1]]
Output: 8

Example 3:

Input: mat = [[5]]
Output: 5
Constraints:

n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100

python解答:

class Solution(object):
    def diagonalSum(self, mat):
        """
        :type mat: List[List[int]]
        :rtype: int
        """
        target = 0
        length = len(mat)
        for i in range(length):
            target += mat[i][i]
            target += mat[i][length-1-i]
        if length % 2 != 0:
            return target - mat[length//2][length//2]
        else:
            return target

1582.二进制矩阵中的特殊位置

Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat.

A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).

Example 1:

Input: mat = [[1,0,0],
              [0,0,1],
              [1,0,0]]
Output: 1
Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.

Example 2:

Input: mat = [[1,0,0],
              [0,1,0],
              [0,0,1]]
Output: 3
Explanation: (0,0), (1,1) and (2,2) are special positions. 

Example 3:

Input: mat = [[0,0,0,1],
              [1,0,0,0],
              [0,1,1,0],
              [0,0,0,0]]
Output: 2

Example 4:

Input: mat = [[0,0,0,0,0],
              [1,0,0,0,0],
              [0,1,0,0,0],
              [0,0,1,0,0],
              [0,0,0,1,1]]
Output: 3
Constraints:

rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j] is 0 or 1.

python解答:

class Solution(object):
    def numSpecial(self, mat):
        """
        :type mat: List[List[int]]
        :rtype: int
        """
        row_len = len(mat)
        col_len = len(mat[0])
        row = [0] * row_len
        col = [0] * col_len
        for i in range(row_len):
            row[i] = sum(mat[i])
        for j in range(col_len):
            col[j] = sum([mat[i][j] for i in range(row_len)])
        target = 0
        col_index = 1
        for i in range(len(row)):
            if row[i] == 1:
                for index in range(col_len):
                    if mat[i][index] == 1:
                        col_index = index
                if col[col_index] == 1:
                    target += 1
        return target

1558.所有奇数长度子数组的和
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.

A subarray is a contiguous subsequence of the array.

Return the sum of all odd-length subarrays of arr.

Example 1:

Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

Example 2:

Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.

Example 3:

Input: arr = [10,11,12]
Output: 66
Constraints:

1 <= arr.length <= 100
1 <= arr[i] <= 1000

python解答:

class Solution(object):
    def sumOddLengthSubarrays(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        target = 0 
        for i in range(len(arr)):
            left = i+ 1
            right = len(arr)-i
            left_even = (left+1)/2
            right_even = (right+1)/2
            left_odd = left/2
            right_odd = right/2
            target += (left_even*right_even+left_odd*right_odd)*arr[i]
        return target 

剑指Offer 03.数组中重复的数字

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 
限制:

2 <= n <= 100000

python解答:

class Solution(object):
    def findRepeatNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # dict1 = {}
        # for item in nums:
        #     if item not in dict1:
        #         dict1[item] = 0
        #     else:
        #         return item
        ## 空间复杂度为O(1)
        i = 0
        while i < len(nums):
            if nums[i] == i:
                i += 1
                continue
            if nums[nums[i]] == nums[i]: 
                return nums[i]
            nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
        return -1

剑指Offer 04.二维数组中的查找

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例:

现有矩阵 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。

给定 target = 20,返回 false。
限制:

0 <= n <= 1000

0 <= m <= 1000

python解答:

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return False
        for i in range(len(matrix)):
            if matrix[i][0] <= target:
                for j in range(0, len(matrix[0])):
                    if matrix[i][j] == target:
                        return True
                    elif matrix[i][j] > target:
                        break
        return False

剑指Offer 29.顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

python解答:

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return []
        ## 模拟
        # row = len(matrix)
        # col = len(matrix[0])
        # index = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        # total = row * col
        # r, c = 0, 0
        # symbol = [[False] * col for i in range(row)]
        # target = [0]*total
        # c_index = 0
        # for i in range(total):
        #     target[i] = matrix[r][c]
        #     symbol[r][c] = True
        #     nextRow, nextColumn = r + index[c_index][0], c + index[c_index][1]
        #     if not (0 <= nextRow < row and 0 <= nextColumn < col and not symbol[nextRow][nextColumn]):
        #         c_index = (c_index+1)%4
        #     r += index[c_index][0]
        #     c += index[c_index][1]
        # return target

        ## 按层模拟
        row = len(matrix)
        col = len(matrix[0])
        target = []
        left, right, top, bottom = 0, col-1, 0, row-1
        while left<=right and top<=bottom:
            for c in range(left, right+1):
                target.append(matrix[top][c])
            for r in range(top+1, bottom+1):
                target.append(matrix[r][right])
            if left<right and top<bottom:
                for c in range(right-1, left, -1):
                    target.append(matrix[bottom][c])
                for r in range(bottom, top, -1):
                    target.append(matrix[r][left])
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        return target

动态规划

70.爬楼梯

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
4. 1 step + 1 step + 1 step
5. 1 step + 2 steps
6. 2 steps + 1 step
Constraints:

1 <= n <= 45

python解答:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        # if n == 1:
        #     return 1
        # i = 1
        # target = 1
        # while i*2 <= n:
        #     num_1 = n - 2*i
        #     index = num_1 + i
        #     if i > (index+1)/2:
        #         i_index = index -i 
        #     else:
        #         i_index = i
        #     molecule, denominator = 1, 1
        #     for m in range(i_index):
        #         molecule *= index-m
        #         denominator *= m+1
        #     target += (molecule/denominator)
        #     i += 1
        # return target
        if n == 1:
            return 1
        num = [0]*n
        num[0] = 1
        num[1] = 2
        for i in range(2, n):
            num[i] = num[i-1] + num[i-2]
        return num[-1]

198.打家劫舍

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:

0 <= nums.length <= 100
0 <= nums[i] <= 400

python解答:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # length = len(nums)
        # if length == 0:
        #     return 0
        # if 0<length <= 2:
        #     return max(nums)
        # target = [0 for i in range(length)]
        # target[0] = nums[0]
        # target[1] = max(nums[0], nums[1])
        # for i in range(2, length):
        #     target[i] = max(target[i-1], target[i-2]+nums[i])
        # return target[-1]
        length = len(nums)
        if length == 0:
            return 0
        if length == 1:
            return nums[0]
        left, right = nums[0], max(nums[0], nums[1])
        for i in range(2, length):
            left, right = right, max(left+nums[i], right)
        return right

303.区域和检索

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Constraints:

You may assume that the array does not change.
There are many calls to sumRange function.
0 <= nums.length <= 10^4
-10^5 <= nums[i] <= 10^5
0 <= i <= j < nums.length

python解答:

class NumArray:

    def __init__(self, nums: List[int]):
        self.target = [0]
        for i in range(len(nums)):
            self.target.append(nums[i]+self.target[i])

    def sumRange(self, i: int, j: int) -> int:
        return self.target[j+1]-self.target[i]


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

392.判断子序列

Given a string s and a string t, check if s is subsequence of t.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).

Follow up:
If there are lots of incoming S, say S1, S2, … , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false
Constraints:

0 <= s.length <= 100
0 <= t.length <= 10^4
Both strings consists only of lowercase characters.

python解答:

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i = 0
        j = 0
        n = len(s)
        m = len(t)
        while i < n and j < m:
            if s[i] == t[j]:
                i += 1
            j += 1
        return i == n

1025.除数博弈

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there is a number N on the chalkboard. On each player’s turn, that player makes a move consisting of:

Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N - x.
Also, if a player cannot make a move, they lose the game.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example 1:

Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:

1 <= N <= 1000

python解答:

class Solution:
   def divisorGame(self, N: int) -> bool:
       if N % 2 == 0:
           return True
       else:
           return False

剑指Offer 42.连续子数组的最大和

输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。

要求时间复杂度为O(n)。

示例1:

输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:

1 <= arr.length <= 10^5
-100 <= arr[i] <= 100

python解答:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        for i in range(1, len(nums)):
            nums[i] += max(nums[i - 1], 0)
        return max(nums)

面试题17.16 按摩师

一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),返回总的分钟数。

注意:本题相对原题稍作改动

示例 1:

输入: [1,2,3,1]
输出: 4
解释: 选择 1 号预约和 3 号预约,总时长 = 1 + 3 = 4。

示例 2:

输入: [2,7,9,3,1]
输出: 12
解释: 选择 1 号预约、 3 号预约和 5 号预约,总时长 = 2 + 9 + 1 = 12。

示例 3:

输入: [2,1,4,5,3,1,1,3]
输出: 12
解释: 选择 1 号预约、 3 号预约、 5 号预约和 8 号预约,总时长 = 2 + 4 + 3 + 3 = 12。

python解答:

class Solution:
    def massage(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        elif len(nums) <= 2:
            return max(nums)
        nums[1] = max(nums[0], nums[1])
        for i in range(2, len(nums)):
            nums[i] = max(nums[i]+nums[i-2], nums[i-1])
        return nums[-1]

字符串

13.罗马数字转整数

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

Example 1:

Input: s = "III"
Output: 3

Example 2:

Input: s = "IV"
Output: 4
Example 3:

Input: s = "IX"
Output: 9

Example 4:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:

1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].

python解答:

class Solution:
    def romanToInt(self, s: str) -> int:
        # d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}
        # target = 0
        # for i, n in enumerate(s):
        #     target += d.get(s[max(i-1, 0): i+1], d[n])
        # return target

        d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        n = len(s)
        Int = 0 
        for index in range(n - 1):
            if(d[s[index]] < d[s[index + 1]]):
                Int = Int - d[s[index]]
            else:
                Int = Int + d[s[index]]
        return Int + d[s[-1]]

14.最长的公共前缀

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string “”.

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:

0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

python解答:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 0:
            return ""
        target = strs[0]
        for item in strs:
            index = 0
            while index < min(len(target), len(item)) and target[index] == item[index]:
                index += 1
            target = item[:index]
        return target

20.有效的括号

Given a string s containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true
Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

python解答:

class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {
            ")":"(", 
            "]": "[",
            "}": "{"
        }
        target = []
        for item in s:
            if item in pairs:
                if not target or target[-1] != pairs[item]:
                    return False
                else:
                    target.pop()
            else:
                target.append(item)
        return not target

28.实现strStr()题解

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Example 3:

Input: haystack = "", needle = ""
Output: 0
Constraints:

0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.

python解答:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle) == 0:
            return 0
        length = len(needle)
        length2 = len(haystack)
        if length > length2:
            return -1
        for i in range(length2 - length + 1):
            if haystack[i] == needle[0]:
                if haystack[i:i+length] == needle:
                    return i
        return -1

38.外观数列

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.

Given an integer n, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
Constraints:

1 <= n <= 30

python解答:

class Solution:
    def countAndSay(self, n: int) -> str:
        if n == 1:
            return "1"
        last_target = "1"
        for i in range(1, n):
            pre = last_target[0]
            count = 0
            target = ""
            for item in last_target:
                if item == pre:
                    count += 1
                else:
                    target += str(count)
                    target += pre
                    count = 1
                pre =item
            target += str(count)
            target += pre
            last_target = target
        return last_target

58.最后一个单词的长度

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

python解答:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        count = 0
        for i in range(len(s)-1, -1, -1):
            if s[i] != ' ':
                count += 1
            elif count > 0:
                return count
        return count

67.二进制求和

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
Constraints:

Each string consists only of '0' or '1' characters.
1 <= a.length, b.length <= 10^4
Each string is either "0" or doesn't contain any leading zero.

python解答:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        len_a = len(a)
        len_b = len(b)
        max_len = max(len_a, len_b)
        a = "0" * (max_len - len_a) + a
        b = "0" * (max_len - len_b) + b
        target = ""
        index = 0
        for i in range(max_len-1, -1, -1):
            m = int(a[i])
            n = int(b[i])
            target = str((m + n + index) % 2) + target
            index = (m + n + index) // 2
        if index > 0:
            target = "1" + target
        return target

125.验证回文串

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false
Constraints:

s consists only of printable ASCII characters.

python解答:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        n = len(s)
        left = 0
        right = n-1
        while left < right:
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1
            if left < right:
                if s[left].lower() != s[right].lower():
                    return False
                left, right = left + 1, right - 1
        return True

344.反转字符串

Write a function that reverses a string. The input string is given as an array of characters char[].

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

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

python解答:

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        length = len(s)
        if length == 0:
            return [""]
        for i in range((length+1)//2):
            # inter = s[length-1-i]
            # s[length-1-i] = s[i]
            # s[i] = inter
            s[i], s[length-1-i] = s[length-1-i], s[i]
        return s

345.反转字符串中的元音字母

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".

python解答:

class Solution:
    def reverseVowels(self, s: str) -> str:
        dic = {'a','e','i','o','u','A','E','I','O','U'}
        left = 0
        right = len(s)-1
        s1 = list(s)
        while left < right:
            while left < right and s1[left] not in dic:
                left += 1
            while left < right and s1[right] not in dic:
                right -= 1
            if left < right:
                s1[left], s1[right] = s1[right], s1[left]
                left += 1
                right -= 1
        return ''.join(s1)

383.赎金信

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:

You may assume that both strings contain only lowercase letters.

python解答:

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        dict1 = {}
        for item in magazine:
            if item in dict1:
                dict1[item] += 1
            else:
                dict1[item] = 1
        for item in ransomNote:
            if item not in dict1:
                return False
            else:
                dict1[item] -= 1
                if dict1[item] < 0:
                    return False
        return True

387.字符串中的第一个唯一字符

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Note: You may assume the string contains only lowercase English letters.

python解答:

class Solution:
    def firstUniqChar(self, s: str) -> int:
        dict1 = {}
        for i in range(len(s)):
            if s[i] not in dict1:
                dict1[s[i]] = i
            else:
                dict1[s[i]] = -1
        for item in dict1:
            if dict1[item] >= 0:
                return dict1[item]
        return -1

415.字符串相加

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

python解答:

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        len_1 = len(num1)
        len_2 = len(num2)
        max_len = max(len_1, len_2)
        num1 = '0' * (max_len-len_1) + num1
        num2 = '0' * (max_len-len_2) + num2
        target = ''
        index = 0
        for i in range(max_len-1, -1, -1):
            m = int(num1[i])
            n = int(num2[i])
            target = str((m+n+index)%10) + target
            index = (m+n+index) // 10
        if index > 0:
            target = str(index) + target
        return target

434.字符串中的单词数

You are given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

Example 3:

Input: s = "love live! mu'sic forever"
Output: 4

Example 4:

Input: s = ""
Output: 0

Constraints:

0 <= s.length <= 300
s consists of lower-case and upper-case English letters, digits or one of the following characters "!@#$%^&*()_+-=',.:".
The only space character in s is ' '

python解答:

class Solution:
    def countSegments(self, s: str) -> int:
        begin = False
        count = 0
        for item in s:
            if item != ' ':
                begin = True
            else:
                if begin:
                    count += 1
                    begin = False
        if begin:
            count += 1
        return count

459.重复的字符串

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"
Output: False

Example 3:

Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

python解答:

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        length = len(s)
        for i in range(length-1):
            div = length % (i+1)
            if div == 0:
                new = s[:i+1] * (length // (i+1))
                if new == s:
                    return True
        return False

520.检测大写字母

Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

All letters in this word are capitals, like “USA”.
All letters in this word are not capitals, like “leetcode”.
Only the first letter in this word is capital, like “Google”.
Otherwise, we define that this word doesn’t use capitals in a right way.

Example 1:

Input: "USA"
Output: True

Example 2:

Input: "FlaG"
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
python解答:

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        count = 0
        for item in word:
            if item >= 'A' and item <= 'Z':
                count += 1
        if (count == 1 and word[0] >= 'A' and word[0] <= 'Z') or count == len(word) or count == 0:
            return True
        return False

521.最长特殊序列1

Given two strings a and b, find the length of the longest uncommon subsequence between them.

A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, “abc” is a subsequence of “aebdc” because you can delete the underlined characters in “aebdc” to get “abc”. Other subsequences of “aebdc” include “aebdc”, “aeb”, and “” (empty string).

An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.

Return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence doesn’t exist, return -1.

Example 1:

Input: a = "aba", b = "cdc"
Output: 3
Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Note that "cdc" is also a longest uncommon subsequence.

Example 2:

Input: a = "aaa", b = "bbb"
Output: 3
Explanation: The longest uncommon subsequences are "aaa" and "bbb".

Example 3:

Input: a = "aaa", b = "aaa"
Output: -1
Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.

Constraints:

1 <= a.length, b.length <= 100
a and b consist of lower-case English letters.

python解答:

class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        length_a = len(a)
        length_b = len(b)
        if a == b:
            return -1
        else:
            return max(length_a, length_b)

541.反转字符串2

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
python解答:

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        s = list(s)
        length = len(s)
        for i in range(0, length, 2*k):
            start = i
            end = min(start+k-1, length-1)
            while start < end:
                m = s[end]
                s[end] = s[start]
                s[start] = m
                start += 1
                end -= 1
        return "".join(s)

551.学生出勤记录1

You are given a string representing an attendance record for a student. The record only contains the following three characters:
‘A’ : Absent.
‘L’ : Late.
‘P’ : Present.
A student could be rewarded if his attendance record doesn’t contain more than one ‘A’ (absent) or more than two continuous ‘L’ (late).

You need to return whether the student could be rewarded according to his attendance record.

Example 1:

Input: "PPALLP"
Output: True

Example 2:

Input: "PPALLL"
Output: False

python解答:

class Solution:
    def checkRecord(self, s: str) -> bool:
        # dict1 = {}
        # dict1['A'] = 0
        count_A = 0
        count_L = 0
        for item in s:
            if item == 'A':
                count_L = 0
                # dict1['A'] += 1
                count_A += 1
                if count_A > 1:
                    return False
            elif item == 'L':
                count_L += 1
                if count_L > 2:
                    return False
            else:
                count_L = 0
        return True

557.反转字符串中的单词3

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.

python解答:

def reverseWords(self, s: str) -> str:
        new_s = ''
        list1 = []
        for item in s:
            if item != ' ':
                list1.append(item)
            else:
                i = 0
                j = len(list1)-1
                while i < j:
                    mid = list1[j]
                    list1[j] = list1[i]
                    list1[i] = mid
                    i += 1
                    j -= 1
                new_s += "".join(list1)
                new_s += ' '
                list1 = []
        i = 0
        j = len(list1)-1
        while i < j:
            mid = list1[j]
            list1[j] = list1[i]
            list1[i] = mid
            i += 1
            j -= 1
        new_s += "".join(list1)
        return new_s

606.根据二叉树创建字符串

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())", 
but you need to omit all the unnecessary empty parenthesis pairs. 
And it will be "1(2(4))(3)".

Example 2:

Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \  
      4 

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example, 
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

python解答:

class Solution:
    def tree2str(self, t: TreeNode) -> str:
        def helper(t):
            if not t:
                return ''
            l = helper(t.left)
            r = helper(t.right)
            if l:
                lstr = '(' + l + ')'
            else:
                if r:
                    lstr = '()'
                else:
                    lstr = ''
            if r:
                rstr = '(' + r + ')'
            else:
                rstr = ''
            return str(t.val) + lstr + rstr
        return helper(t)

657.机器人能否返回原点

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is “facing” is irrelevant. “R” will always make the robot move to the right once, “L” will always make it move left, etc. Also, assume that the magnitude of the robot’s movement is the same for each move.

Example 1:

Input: moves = "UD"
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

Input: moves = "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

Example 3:

Input: moves = "RRDD"
Output: false

Example 4:

Input: moves = "LDRRLRUULR"
Output: false

Constraints:

1 <= moves.length <= 2 * 104
moves only contains the characters 'U', 'D', 'L' and 'R'.

python解答:

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        u = 0
        l = 0
        for item in moves:
            if item == 'R':
                l += 1
            elif item == 'L':
                l -= 1
            elif item == 'U':
                u += 1
            else:
                u -= 1
        if u == 0 and l == 0:
            return True
        else:
            return False

680.验证回文字符串2

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:

Input: "aba"
Output: True

Example 2:

Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Note:

The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

python解答:

class Solution:
    def validPalindrome(self, s: str) -> bool:
        def check(i ,j):
            l = i
            r = j
            while l < r:
                if s[l] == s[r]:
                    l += 1
                    r -= 1
                else:
                    return False
            return True
        s = list(s)
        left = 0
        right = len(s)-1
        delete = False
        while left < right:
            if s[left] == s[right]:
                left += 1
                right -= 1
            else:
                if delete:
                    return False
                else:
                    if check(left+1, right) or check(left, right-1):
                        return True
                    else:
                        return False
        return True

696.计数二进制子串

Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.

Substrings that occur multiple times are counted the number of times they occur.

Example 1:

Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".

Notice that some of these substrings repeat and are counted the number of times they occur.

Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

Example 2:

Input: "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Note:

s.length will be between 1 and 50,000.
s will only consist of "0" or "1" characters.

python解答:

class Solution:
    def countBinarySubstrings(self, s: str) -> int:
        list1 = []
        count = 1
        for i in range(1, len(s)):
            if s[i] == s[i-1]:
                count += 1
            else:
                list1.append(count)
                count = 1
        list1.append(count)
        target = 0
        for i in range(1, len(list1)):
            target += min(list1[i], list1[i-1])
        return target

709.转换成小写字母

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example 1:

Input: "Hello"
Output: "hello"

Example 2:

Input: "here"
Output: "here"

Example 3:

Input: "LOVELY"
Output: "lovely"

python解答:

class Solution:
    def toLowerCase(self, str: str) -> str:
        s = []
        for i in str:
            if  65 <= ord(i) <= 90:
                s.append(chr(ord(i) + 32))
            else:
                s.append(i)
        return ''.join(s)

788.旋转数字

X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other (on this case they are rotated in a different direction, in other words 2 or 5 gets mirrored); 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

Example:

Input: 10
Output: 4
Explanation: 
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

Note:
N will be in range [1, 10000].
python解答:

class Solution:
    def rotatedDigits(self, N: int) -> int:
        count = 0
        for i in range(1, N+1):
            m = str(i)
            if '3' not in m and '4' not in m and '7' not in m:
                if '2' in m or '5' in m or '6' in m or '9' in m:
                    count += 1
        return count

804.唯一摩尔斯密码词

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: “a” maps to “.-”, “b” maps to “-…”, “c” maps to “-.-.”, and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, “cab” can be written as “-.-…–…”, (which is the concatenation “-.-.” + “.-” + “-…”). We’ll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

Example:

Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation: 
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

There are 2 different transformations, "--...-." and "--...--.".

Note:

The length of words will be at most 100.
Each words[i] will have length in range [1, 12].
words[i] will only consist of lowercase letters.

python解答:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        list1 = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        target = []
        for item in words:
            s = ""
            for word in item:
                s += list1[ord(word)-ord('a')]
            target.append(s)
        dict1 = {}
        for item in target:
            if item not in dict1:
                dict1[item] = 1
        return len(dict1)

819.最常见的单词

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.

Example:

Input: 
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation: 
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"), 
and that "hit" isn't the answer even though it occurs more because it is banned.

Note:

1 <= paragraph.length <= 1000.
0 <= banned.length <= 100.
1 <= banned[i].length <= 10.
The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
There are no hyphens or hyphenated words.
Words only consist of letters, never apostrophes or other punctuation symbols.

python解答:

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        for c in "!?',;.":
            paragraph = paragraph.replace(c, " ")
        ban = set(banned)
        max_value = 0
        target = -1
        dict1 = {}
        for item in paragraph.split():
            item = item.lower()
            if item not in ban:
                if item not in dict1:
                    dict1[item] = 1
                else:
                    dict1[item] += 1
                if dict1[item] > max_value:
                    max_value = dict1[item]
                    target = item
        return target

824.山羊拉丁文

A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

If a word begins with a vowel (a, e, i, o, or u), append “ma” to the end of the word.
For example, the word ‘apple’ becomes ‘applema’.

If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add “ma”.
For example, the word “goat” becomes “oatgma”.

Add one letter ‘a’ to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets “a” added to the end, the second word gets “aa” added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.

Example 1:

Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Notes:

S contains only uppercase, lowercase and spaces. Exactly one space between each word.
1 <= S.length <= 150.

python解答:

class Solution:
    def toGoatLatin(self, S: str) -> str:
        s = S.split()
        ower = ['a', 'e', 'i', 'o', 'u']
        for i in range(len(s)):
            if s[i][0].lower() in ower:
                s[i] += 'ma'
            else:
                s[i] = s[i][1:] + s[i][0] +'ma'
            s[i] += 'a'* (i+1)
        return ' '.join(s)

859.亲密字符串

Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in “abcd” results in “cbad”.

Example 1:

Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.

Example 2:

Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.

Example 3:

Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:

Input: A = "", B = "aa"
Output: false

Constraints:

0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist of lowercase letters.

python解答:

class Solution:
    def buddyStrings(self, A: str, B: str) -> bool:
        if len(A) != len(B):
            return False
        if A == B:
            dict1 = {}
            for item in A:
                if item not in dict1:
                    dict1[item] = 1
                else:
                    dict1[item] += 1
                if dict1[item] >= 2:
                    return True
            return False
        else:
            target = []
            for i in range(len(A)):
                if A[i] != B[i]:
                    target.append(i)
                if len(target) == 2:
                    if A[target[0]] != B[target[1]] or A[target[1]] != B[target[0]]:
                        return False
                elif len(target) > 2:
                    return False
            if len(target) == 1:
                return False
            return True

893.特殊等价字符串组

You are given an array A of strings.

A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.

Two strings S and T are special-equivalent if after any number of moves onto S, S == T.

For example, S = “zzxy” and T = “xyzz” are special-equivalent because we may make the moves “zzxy” -> “xzzy” -> “xyzz” that swap S[0] and S[2], then S[1] and S[3].

Now, a group of special-equivalent strings from A is a non-empty subset of A such that:

Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn’t a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.

Example 1:

Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation: 
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.

The other two groups are ["xyzz", "zzxy"] and ["zzyx"].  Note that in particular, "zzxy" is not special equivalent to "zzyx".

Example 2:

Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3

Note:

1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters.

python解答:

class Solution:
    def numSpecialEquivGroups(self, A: List[str]) -> int:
        odd = []
        even = []
        for item in A:
            odd.append(sorted([item[i] for i in range(1, len(item), 2)]))
            even.append(sorted([item[i] for i in range(0, len(item), 2)]))
        dict1 = {}
        for i in range(len(odd)):
            s = odd[i] + even[i]
            s = ''.join(s)
            if s in dict1:
                dict1[s] += 1
            else:
                dict1[s] = 1
        return len(dict1)

917.仅仅反转字母

Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

S.length <= 100
33 <= S[i].ASCIIcode <= 122 
S doesn't contain \ or "

python解答:

class Solution:
    def reverseOnlyLetters(self, S: str) -> str:
        index_symbol = {}
        l = []
        for i in range(len(S)):
            if not S[i].isalpha():
                index_symbol[i] = S[i]
            else:
                l.append(S[i])
        target = ''
        j = len(l)-1
        for i in range(len(S)):
            if i not in index_symbol:
                target += l[j]
                j -= 1
            else:
                target += index_symbol[i]
        return target

925.长按键入

Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

Example 1:

Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.

Example 2:

Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.

Example 3:

Input: name = "leelee", typed = "lleeelee"
Output: true

Example 4:

Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.

Constraints:

1 <= name.length <= 1000
1 <= typed.length <= 1000
The characters of name and typed are lowercase letters.

python解答:

class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        i, j = 0, 0
        while (j < len(typed)):
            if i < len(name) and name[i] == typed[j]:
                i += 1
                j += 1
            elif j > 0 and typed[j] == typed[j-1]:
                j += 1
            else:
                return False
        return i == len(name)

929.独特的电子邮件地址

Every email consists of a local name and a domain name, separated by the @ sign.

For example, in [email protected], alice is the local name, and leetcode.com is the domain name.

Besides lowercase letters, these emails may contain '.'s or '+'s.

If you add periods (’.’) between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, “[email protected]” and “[email protected]” forward to the same email address. (Note that this rule does not apply for domain names.)

If you add a plus (’+’) in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example [email protected] will be forwarded to [email protected]. (Again, this rule does not apply for domain names.)

It is possible to use both of these rules at the same time.

Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?

Example 1:

Input: ["[email protected]","[email protected]","[email protected]"]
Output: 2
Explanation: "[email protected]" and "[email protected]" actually receive mails

Note:

1 <= emails[i].length <= 100
1 <= emails.length <= 100
Each emails[i] contains exactly one '@' character.
All local and domain names are non-empty.
Local names do not start with a '+' character.

python解答:

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        dict1 = {}
        for item in emails:
            symbol_jia = False
            symbol_yu = False
            s = ""
            for ele in item:
                if not symbol_jia and not symbol_yu:
                    if ele == '.':
                        s = s
                    elif ele == '+':
                        symbol_jia = True
                    elif ele == '@':
                        symbol_yu = True
                        s += ele
                    else:
                        s += ele
                elif symbol_jia:
                    if ele == '@':
                        symbol_jia = False
                        symbol_yu = True
                        s += ele
                elif not symbol_jia and symbol_yu:
                    s += ele
            if s not in dict1:
                dict1[s] = 1
        return len(dict1)

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

;