LeetCode Week3

来源:互联网 发布:office mac 破解 威锋 编辑:程序博客网 时间:2024/05/23 22:44

LeetCode Week3

EX. 566

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.

Example1:

Input: nums = [[1,2],[3,4]]r = 1, c = 4Output: [[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.

Example2:

Input: nums = [[1,2],[3,4]]r = 2, c = 4Output: [[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.

Solution:

1.两层循环,将符合要求的vector塞至结果vector即可

class Solution {public:    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {        if (r*c != nums.size()*nums[0].size())            return nums;        vector<vector<int>> res;        vector<int> temp;        int sum = 0, i = 0, index = 0, turn = 0, max = nums[0].size();        while (turn < r) {            while (sum < c) {                if (i == max) {                    i = 0;                    index++;                }                temp.push_back(nums[index][i]);                sum++;                i++;            }            res.push_back(temp);            temp.clear();            sum = 0;            turn++;        }        return res;    }};

EX.442

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

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

Solution:

因为数字的大小范围为1~N,所以只需要在循环中运用木桶原则,判断是否在其该处的位置,不在则将其与该处位置的数交换,如果在正确的位置,则继续往前。最后遍历出在错误位置的数,即是重复的数。

class Solution {public:    vector<int> findDuplicates(vector<int>& nums) {        int i = 0;        vector<int> res;        while (i < nums.size()) {            if (nums[i] != nums[nums[i] - 1])                swap(nums[i], nums[nums[i] - 1]);            else i++;        }        for (i = 0; i < nums.size(); i++) {            if (nums[i] != i + 1)                res.push_back(nums[i]);        }        return res;    }};
原创粉丝点击