• Leetcode with Python -> Array


    118. Pascal's Triangle

    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    class Solution(object):
        def generate(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            """
            res = [[1]]
            for i in range(1,numRows):
                res += [map(lambda x, y:x+y,res[-1]+[0],[0]+res[-1])]
            return res[:numRows]
        
        # [[1]]+[0] -> [[1],0]
        # [[1]]+[0,1] ->[[1],0,1]
        # [[1]]+[[0]] -> [[1],[0]]
        # [[1]]+0 -> error
        # the code is elegant, but slow. the reason lies in the fact that it generates too much list while looping
        # be careful when numRows is 0, res[:numRows] will return [] when it happens

    119. Pascal's Triangle II

    Given an index k, return the kth row of the Pascal's triangle.

    For example, given k = 3,
    Return [1,3,3,1].

    Note:
    Could you optimize your algorithm to use only O(k) extra space?

    class Solution(object):
        def getRow(self, rowIndex):
            """
            :type rowIndex: int
            :rtype: List[int]
            """
    
            
            res = [1]
            for i in range(0, rowIndex):
                res = [ i+j for i,j in zip(res + [0], [0] + res)]
            return res
        
        # list can't be added elementwisely with +
    

    561. Array Partition I

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

    Note:

    1. n is a positive integer, which is in the range of [1, 10000].
    2. All the integers in the array will be in the range of [-10000, 10000].
    class Solution(object):
        def arrayPairSum(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            sorted_nums=sorted(nums)
            return sum(sorted_nums[::2])
            # easy but not fast

    566. Reshape the Matrix

    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.

    Note:

    1. The height and width of the given matrix is in range [1, 100].
    2. The given r and c are all positive
    class Solution(object):
        def matrixReshape(self, nums, r, c):
            """
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            """
            if r*c != len(nums)*len(nums[0]):
                return nums
            else:
                newList = [y for x in nums for y in x]
                return [newList[i*c:i*c+c] for i in range(r)]
            # not difficult
            
    

    643. Maximum Average Subarray I

    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. 1 <= k <= n <= 30,000.
    2. Elements of the given array will be in the range [-10,000, 10,000].
    class Solution(object):
        def findMaxAverage(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: float
            """
            sum_max=sum(nums[:k])
            cur_sum=sum_max
            for i in range(k,len(nums)):
                cur_sum=cur_sum+nums[i]-nums[i-k]
                if cur_sum>sum_max:
                    sum_max=cur_sum
            return float(sum_max)/k
        # the difference between '/' and '//' only exist in python3, not 2
        # clear and fast
                
    

    661. Image Smoother

    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:

    1. The value in the given matrix is in the range of [0, 255].
    2. The length and width of the given matrix are in the range of [1, 150].
    class Solution(object):
        def imageSmoother(self, M):
            """
            :type M: List[List[int]]
            :rtype: List[List[int]]
            """
            r=len(M)
            c=len(M[0])
            for i in range(r):
                M[i].append(-1) 
            M.append([-1 for i in range(c+1)])
            N=[[0 for j in range(c)] for i in range(r)]
            for i in range(r):
                for j in range(c):
                    count = 0
                    sum_temp=0
                    for k in range(-1,2):
                        for l in range(-1,2):
                            if M[i+k][j+l] != -1:
                                count+=1
                                sum_temp+=M[i+k][j+l]
                    N[i][j]=sum_temp/count
            return N
        # use -1 to distinguish the arti_added elements
        # utilize index -1 in python to optimize the realization 

    665. Non-decreasing Array

    Given an array 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 array[i] <= array[i + 1] holds for every i (1 <= i < n).

    Example 1:

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

    Example 2:

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

    Note: The n belongs to [1, 10,000].

    class Solution(object):
        def checkPossibility(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            cur, nxt = nums[:], nums[:]
            for i in range(len(nums)-1):
                if nums[i]>nums[i+1]:
                    cur[i]=nums[i+1]
                    nxt[i+1]=nums[i]
                    break
            if cur==sorted(cur) or nxt==sorted(nxt):
                return True
            return False
        # "==" can be used between lists, good!
        # sorted() will return a new list

    674. Longest Continuous Increasing Subsequence

    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.

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

    695. Max Area of Island

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    Example 1:

    [[0,0,1,0,0,0,0,1,0,0,0,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,1,1,0,1,0,0,0,0,0,0,0,0],
     [0,1,0,0,1,1,0,0,1,0,1,0,0],
     [0,1,0,0,1,1,0,0,1,1,1,0,0],
     [0,0,0,0,0,0,0,0,0,0,1,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    

    Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

    Example 2:

    [[0,0,0,0,0,0,0,0]]

    Given the above grid, return 0.

    Note: The length of each dimension in the given grid does not exceed 50.

    class Solution(object):
        def maxAreaOfIsland(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            
            row,col = len(grid),len(grid[0])
            
            def dfs(i,j):
                
                if 0<=i<row and 0<=j<col and grid[i][j] == 1:
                    grid[i][j]=0
                    return 1+dfs(i-1,j)+dfs(i+1,j)+dfs(i,j-1)+dfs(i,j+1)
                else:
                    return 0
            
            island = [dfs(i,j) for i in range(row) for j in range(col) if grid[i][j]]
            
            return max(island) if island else 0
        
        # make it faster when not busy
        
        

    697. Degree of an Array

    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: [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: [1,2,2,3,1,4,2]
    Output: 6
    

    Note:

    • nums.length will be between 1 and 50,000.
    • nums[i] will be an integer between 0 and 49,999.
    class Solution(object):
        def findShortestSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            dic = {}
            for i in range(len(nums)):
                if nums[i] not in dic.keys():
                    dic[nums[i]]=[]
                dic[nums[i]].append(i)
            len_max = max(map(len,dic.values()))
            shortest = 50000
            for i in dic.itervalues():
                if len(i) == len_max:
                    if i[-1]-i[0]+1 < shortest:
                        shortest = i[-1]-i[0]+1
            return shortest
        # too slow
        # dic_obj.itervalues()

    724. Find Pivot Index

    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 the numbers to the left of the index is equal to the sum of 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.
    

    Note:

    • The length of nums will be in the range [0, 10000].
    • Each element nums[i] will be an integer in the range [-1000, 1000].

     

    class Solution(object):
        def pivotIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if nums==[]:
                return -1
            nums_sum=sum(nums)
            cur_sum= 0
            found = 0
            for i in range(len(nums)):
                if cur_sum*2 == nums_sum-nums[i]:
                    found =1
                    return i
                cur_sum += nums[i]
            if found == 0: return -1
            # lele tested me with this before

    747. Largest Number At Least Twice of Others

    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:

    1. nums will have a length in the range [1, 50].
    2. Every nums[i] will be an integer in the range [0, 99].
    class Solution(object):
        def dominantIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    
            max = 0
            notfound = 0
            for i in range(len(nums))[1:]:
                if notfound == 1:
                    # if the previous array has not found the ideal number(even though max has recorded the index of the largest element), the variable will be alter to 0 only if the i-th element is greater than twice of the max_th element
                    if nums[i]>=nums[max]*2:
                        notfound = 0
                        max = i
                    elif nums[i]>nums[max]:
                        temp = max
                        max = i
                        i = temp
                elif notfound == 0:
                    # if the previous array has found the ideal number(with max being its index), the ith element should either be greater than the max_th element or smaller than 1/2 of it, or, the current array has not found the ideal element, that is , notfound should be set to 1
                    if nums[i]>nums[max]:
                        temp = max
                        max = i
                        i = temp
                    if nums[max]>=nums[i]*2:
                        notfound = 0
                    else:
                        notfound = 1
            if notfound == 1:
                return -1
            else:
                return max
            
    
                
                
    
  • 相关阅读:
    ssd笔记
    深度学习 参数笔记
    NVIDIA驱动安装
    下载大文件笔记
    vue中使用echart笔记
    torch.no_grad
    暑期第二周总结
    暑期第一周总结
    第十六周学习进度
    期末总结
  • 原文地址:https://www.cnblogs.com/DianeSoHungry/p/8111533.html
Copyright © 2020-2023  润新知