leetcode数组部分习题解答(python)part.1

此部分是选自leetcode数组部分的五道简单的练习题总结,也当做自己的总结
**

1.俩数之和

**
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

方法解析:
这是一个典型的数组问题,函数的输入是数组和目标值,只要设置俩个标记,在数组中遍历(第一个标记i保持不变,让标记j遍历除了i以外的其他数,直到标记i遍历完整个数组),判断和是否等于目标值

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in xrange(len(nums)):
            for j in xrange(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return[i,j]

nums = [2,7,11,15]
target = 9
s = Solution()
print(s.twoSum(nums, target))

2.转置矩阵

给定一个矩阵 A, 返回 A 的转置矩阵。矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

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

方法解析:
对于矩阵的操作也是数组考察的重点。
这里介绍一个函数:
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中:

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

在这道题中,我们要先取出矩阵的行和列的数目,再用此生成一个同样大小的空矩阵用来存储返回的目标矩阵,用enumerate()函数来获取矩阵的行号列号以及同时获取行列中对应的值(第一个enumerate函数取出的是行号和当前行的数据,第二个enumerate取出的是矩阵的列号,和由行号列号确定的矩阵值)

class Solution(object):
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        R, C = len(A), len(A[0])
        ans = [[None] * R for _ in range(C)]
        for r, row in enumerate(A):
            for c, val in enumerate(row):
                ans[c][r] = val
        return ans

3.数组拆分

给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), …, (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。

示例 1:
输入: [1,4,3,2]
输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4)

方法解析:
这其实是一个数组排序问题,要想数组中俩俩组合的最小值和最大,就要确保不能浪费数组中的较大的数据,比如【1,2,3,5】中,要让1和2组合,如果让1,3组合,就浪费了3,从而取不到最大,所以组合的思路就是生序排序数组,依次俩俩组合,才能和最大。

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        listNum = list(nums)
        listNum.sort()
        sum = 0
        for i in range(0, len(listNum), 2):
            sum += listNum[i]
        return sum

4. 杨辉三角1

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

leetcode数组部分习题解答(python)part.1_第1张图片

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
方法解析:
这种题型,应抓住这种特殊矩阵的特点。杨辉三角的特点:
1.杨辉三角每一行的列表的数目,是等于其行数的。
2.杨辉三角的每个数都是上一行同列数加上上一行前一列数的和。
抓住这些特征,就很好解题了

class Solution(object):
    def generate(self,numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """

        res = []
        if not numRows:
            return res
        for i in range(numRows):
            tem = [1] * (i+1)
            res.append(tem)
            for j in range(1, i):
                res[i][j] = res[i-1][j-1] + res[i-1][j]
        return res

重塑矩阵

在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

示例 1:
输入:
nums = [[1,2],[3,4]]
r = 1, c = 4
输出: [[1,2,3,4]]
解释:
行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。

方法解析:
先将原数组按行输入到新的列表里,再以目标矩阵的列数为片段长度,以片段的方式输入到目标矩阵里

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        a = len(nums)
        b = len(nums[0])
        res = []
        if a * b < r *c:
            return nums
        else:
            t = []
            for i in range(len(nums)):
                for j in range(len(nums[0])):
                    t.append(nums[i][j])
            m= 0
            for i in range(r):
                res.append(t[m:m+c])
                m+=c
        return res

你可能感兴趣的:(算法,leetcode,面试题)