当前位置:网站首页>[array]566 Reshape the matrix - simple
[array]566 Reshape the matrix - simple
2022-07-05 03:50:00 【51CTO】
stay MATLAB in , There's a very useful function reshape , It can put a m x n The matrix is remodeled to another different size (r x c) The new matrix of , But keep its original data .
Give you a two-dimensional array mat It means m x n matrix , And two positive integers r and c , Represent the number of rows and columns of the matrix to be reconstructed respectively .
The reconstructed matrix needs to replace all elements of the original matrix with the same Row traversal order fill .
If the reshape The operation is feasible and reasonable , The new reshaping matrix is output ; otherwise , Output raw matrix .
Example 1:
Input :mat = [[1,2],[3,4]], r = 1, c = 4
Output :[[1,2,3,4]]
Example 2:
Input :mat = [[1,2],[3,4]], r = 2, c = 4
Output :[[1,2],[3,4]]
Tips :
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
source : Power button (LeetCode)
link :https://leetcode.cn/problems/reshape-the-matrix
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Answer key
Ideas :
- Judge whether the number of input matrices and the number of output matrices are equal
- Apply for space for the output matrix
- Traverse the original matrix , Move the original matrix elements to the output matrix
The code is as follows :
using namespace std;
class Solution
{
public:
vector < vector < int >> matrixReshape( vector < vector < int >> & mat, int r, int c)
{
if ( mat. empty())
{
return mat;
}
int m = mat. size();
int n = mat[ 0]. size();
if ( m * n != r * c)
{
return mat;
}
std::vector < std::vector < int >> ans( r, std::vector < int >( c, 0));
int t = 0;
for ( int i = 0; i < m; ++ i)
{
for ( int k = 0; k < n; ++ k)
{
ans[ t / c][ t % c] = mat[ i][ k];
t ++;
}
}
return ans;
}
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
A few more sentences
leetcode The running time of the upper and lower parts is even faster than mine ( my 12ms), It's ridiculous , First look at leetcode Given 8ms Code for .
class Solution {
public:
vector < vector < int >> matrixReshape( vector < vector < int >>& mat, int r, int c) {
int m = mat. size();
int n = mat[ 0]. size();
int num = 0;
vector < int > s;
vector < vector < int >> mat1( r, vector < int >( c)); // The value can only be assigned after the initialization size
if( m * n != r * c)
{
return mat;
}
for( int i = 0; i < m; i ++)
{
for( int j = 0; j < n; j ++)
{
s. push_back( mat[ i][ j]);
}
}
for( int i = 0; i < r; i ++)
{
for( int j = 0; j < c; j ++)
{
mat1[ i][ j] = s[ num];
num ++;
}
}
return mat1;
}
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
This code is not only one more than me vector, And there are all kinds of elements push_back, These are extra expenses , It's faster than mine ,leetcode It's really painful to judge the time .
Of course, my code above can also be optimized , We know CPU There is a cache , If the cache hit rate is high , Then the program can run faster . If you can reduce the calculation , Then improve the efficiency of the program . We can optimize from the last cycle , The optimized code is as follows :
using namespace std;
class Solution
{
public:
vector < vector < int >> matrixReshape( vector < vector < int >> & mat, int r, int c)
{
if ( mat. empty())
{
return mat;
}
int m = mat. size();
int n = mat[ 0]. size();
int total_count = m * n;
if ( total_count != r * c)
{
return mat;
}
std::vector < std::vector < int >> ans( r, std::vector < int >( c, 0));
for ( int i = 0; i < total_count; ++ i)
{
ans[ i / c][ i % c] = mat[ i / n][ i % n];
t ++;
}
return ans;
}
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
This code is officially known to achieve 0ms, But it's been tested ,1 Next is 8ms,1 Next is 4ms, Honey operation ~~~
Optimization of the 2 The first point is as follows :
- take 2 individual for Cycle to 1 individual , Can increase cpu shooting
- Calculate ahead of time m*n, Um. , This is trivial ~~~
边栏推荐
- Une question est de savoir si Flink SQL CDC peut définir le parallélisme. Si le parallélisme est supérieur à 1, il y aura un problème d'ordre?
- speed or tempo in classical music
- 已解决(sqlalchemy+pandas.read_sql)AttributeError: ‘Engine‘ object has no attribute ‘execution_options‘
- Google Chrome CSS will not update unless the cache is cleared - Google Chrome CSS doesn't update unless clear cache
- Redis source code analysis: redis cluster
- English essential vocabulary 3400
- Leetcode42. connect rainwater
- Blue Bridge Cup single chip microcomputer -- PWM pulse width modulation
- ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
- 【无标题】
猜你喜欢
Basic function learning 02
How about programmers' eyesight| Daily anecdotes
Share the newly released web application development framework based on blazor Technology
Redis source code analysis: redis cluster
PlasticSCM 企业版Crack
Clickhouse materialized view
[vérification sur le Web - divulgation du code source] obtenir la méthode du code source et utiliser des outils
Clickhouse同步mysql(基于物化引擎)
深度学习——LSTM基础
How to define a unified response object gracefully
随机推荐
Ubantu disk expansion (VMware)
已解决(sqlalchemy+pandas.read_sql)AttributeError: ‘Engine‘ object has no attribute ‘execution_options‘
Flex flexible layout
[groovy] loop control (number injection function implements loop | times function | upto function | downto function | step function | closure can be written outside as the final parameter)
[software reverse analysis tool] disassembly and decompilation tool
花了2晚,拿到了吴恩达@斯坦福大学的机器学习课程证书
Nmap使用手册学习记录
Clean up PHP session files
[web Audit - source code disclosure] obtain source code methods and use tools
【无标题】
MySQL winter vacation self-study 2022 11 (9)
It took two nights to get Wu Enda's machine learning course certificate from Stanford University
grandMA2 onPC 3.1.2.5的DMX参数摸索
Monitoring web performance with performance
Une question est de savoir si Flink SQL CDC peut définir le parallélisme. Si le parallélisme est supérieur à 1, il y aura un problème d'ordre?
我就一写代码的,王总整天和我谈格局...
Difference between MotionEvent. getRawX and MotionEvent. getX
[C language] address book - dynamic and static implementation
問下,這個ADB mysql支持sqlserver嗎?
[summary of two registration methods]