Leetcode刷题——Day1

一边看算法,一边刷题吧,先从简单的开始:
刷题之路这就开始了?

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

思路:

就是先排序,每隔一个加到sum中去

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum=0
        nums=sorted(nums)
        j=0
        n=int(len(nums)/2)
        for i in range(n):
            sum+=nums[j]
            j+=2
        return sum

注意:

需要注意sort()函数没有返回值!没有返回值!没有返回值!sorted()函数就很厉害了~~

766. Toeplitz Matrix

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:
1234
5123
9512

思路:

我的想法是如果是一个m*n的矩阵,对角线位置的元素下标i-j的范围可以有k=m+n-1种,然后对每一种情况进行遍历,先检查matrix[j] [j+diff] 是不是合理的元素,然后存到列表中,每一行都遍历完之后(此时这个列表中存的就是下标差满足diff的所有元素 其实也就是对角元素) 然后利用数组的set()函数的性质,查看set之后长度是不是为1,来判断该矩阵是不是满足条件,,嗯,我也不知道为什么想的这么复杂,,,,

class Solution(object):
    def isToeplitzMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: bool
        """
        m=len(matrix)
        n=len(matrix[0])
        k=m+n-1  # the number of the diagoal
        diff=1-m
        for i in range(k):
            L=[]

            for j in range(m):
                for s in range(n): 
                    if 0<=(j+diff)<n:
                        L.append(matrix[j][j+diff])

            if len(set(L))!=1:
                return False
            diff+=1

        else:
            return True

这一题我写的不好,然后看了一下别人的思路是这样的:
就是对于每一行,比较该行matrix[i][0:n-1] 和下一行matrix[i+1][1:]元素值是不是相等,,,,真的是完爆。。

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

思路:

其实这一题很简单,,,刚开始想复杂了,首先把矩阵变成一行,其实可以直接使用numpy的ravel()函数,可是在leetcode老是不能运行,就自己手写了一个,,,然后就正常按矩阵元素存储即可,简单。


class Solution(object):
    def matrixReshape(self,nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        row,column=len(nums),len(nums[0])
        if row*column==r*c:
            L=[]
            for x in range(row):
                for y in range(column):
                    L.append(nums[x][y])
            L_new=[]
            for i in range(r):
                L1=[]
                for j in range(c):
                    L1.append(L[i*c+j])
                L_new.append(L1)
            return L_new         

        else:
            return nums

485. Max Consecutive Ones

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.
Note:

The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000

思路:

首先就是需要考虑几种特殊情况:输入的列表为空,只有一个元素,主要是我刚开始写的程序 在这两种情况下都会报错,发现之后果断换了一种写法,这一题也特别简单,就是比较,更新max的过程嘛。
这一题的运行时间超过90%以上用户哦~~

class Solution:
    def findMaxConsecutiveOnes(self,nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n,max=0,0
        if len(nums)==0:
            return 0
        else:
            for i in nums:
                if i!=1:
                    n=0
                else:
                    n+=1
                if max<n:
                    max=n

            return max

猜你喜欢

转载自blog.csdn.net/jiaowosiye/article/details/80270648