LeetCode-516-ReshapeTheMatrix


LeetCode-516-ReshapeTheMatrix

题目链接

516重塑矩阵

题目描述

在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。

给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。

如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

示例

示例 1:

输入:mat = [[1,2],[3,4]], r = 1, c = 4
输出:[[1,2,3,4]]

示例 2:

输入:mat = [[1,2],[3,4]], r = 2, c = 4
输出:[[1,2],[3,4]]

提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300

题解

题解一:

    /**
     * 思路:暴力破解,假设在第m天买(卖)股票,在n天卖(卖)收益最大
     * 时间复杂度:O(n^2)
     * 空间复杂度:O(1)
     *
     * @param prices 股价数组
     * @return 最大收益
     */
    public int maxProfit1(int[] prices) {
        int maxProfit = 0;
        for (int i = 0; i < prices.length -1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[j] > prices[i]) {
                    maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
                }
            }
        }
        return maxProfit;
    }

题解二:

    /**
     * 思路:将问题分割成最小单位
     *      第一天:只能买到股票
     *      第二天:如果当日股价比购入价高,售出可获得收益,记录收益最大值
     *             如果当日股价比购入价低,我们应该在该日购入股票,无收益
     *      第n天:同n-1天
     * 时间复杂度:O(n)
     * 空间复杂度:O(1)
     *
     * @param prices 股价数组
     * @return 最大收益
     */
    public int maxProfit2(int[] prices) {
        int maxProfit = 0;
        int buyPrice = prices[0];
        for (int price : prices) {
            if (price < buyPrice) {
                buyPrice = price;
            } else {
                maxProfit = Math.max(maxProfit, price - buyPrice);
            }
        }
        return maxProfit;
    }

文章作者: Tariq
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Tariq !
  目录