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; }};
- Leetcode Week3
- leetcode week3
- LeetCode Week3
- leetcode-month1-week3
- LeetCode题解 week3
- Week3
- week3
- week3
- week3
- week3
- LeetCode#5 Longest Palindromic Substring (week3)
- Leetcode: 15. 3Sum(Week3,Medium)
- 算法设计Week3 LeetCode Algorithms Problem #133 Clone Graph
- LeetCode Week3: Different Ways to Add Parentheses、Expression Add Operators
- week3-leetcode #3-Longest Substring Without Repeating Characters[Medium]
- [LeetCode-Algorithms-23] "Merge k Sorted Lists" (2017.9.22-WEEK3)
- [LeetCode-Algorithms-13] "Roman to Integer" (2017.9.22-WEEK3)
- test Week3
- 基于ssm的场地管理系统
- 泛型
- Java9 进程API
- Spring 学习(三)注解装配
- Gym 101512K
- LeetCode Week3
- 学习VUE2.0入门到进阶路线推荐
- 聚类和EM算法
- 利用ztree实现树搜索
- TCP和UDP的区别
- Unity Movement AI (二)
- bootstrap网格布局原理解析
- java任务--打印时间
- Memcache的分布式介绍