LeetCode Daily: Convert 1D Array Into 2D Array Solution in Java | September 1, 2024

preview_player
Показать описание
🔍 LeetCode Problem of the Day: Convert 1D Array Into 2D Array

In today's LeetCode daily challenge, we solve the problem of converting a 1D array into a 2D array given the dimensions m and n, using Java.

👉 Solution: Pinned on the comments

🌟 Problem Description:
Given a 1D array of integers and two integers m and n, the task is to reshape the 1D array into a 2D array with m rows and n columns. If the reshape is not possible, return an empty 2D array.

🔑 Key Points:
Array Validation: First, we check if the product of m and n equals the length of the original array. If not, the reshape is impossible, and we return an empty array.
Reshaping: The original array is split into subarrays of length n and arranged into the m x n 2D array using the copyOfRange method.
Efficiency: The solution efficiently transforms the array using simple loops and Java’s array utilities.

📝 Code Explanation:
Validation: The code first checks if the reshape is possible by comparing the length of the original array with m * n.
Array Transformation: If valid, it uses a loop to split the array and copy elements into the new 2D array.
Return Result: Finally, the constructed 2D array is returned.

📅 Daily Solutions:
Subscribe and hit the bell icon for daily LeetCode solutions, explained step-by-step!

👥 Join the Community:
Share your thoughts on the problem in the comments.
Discuss different approaches with fellow coders.
If you enjoyed this video, please like, share, and subscribe for more daily coding challenges!

#LeetCode #Coding #Programming #TechInterview #ArrayManipulation #DailyChallenge #Java
Рекомендации по теме
Комментарии
Автор

code:
class Solution {
public int[][] construct2DArray(int[] original, int m, int n) {
int len = original.length;

if(len != (m * n))
return new int[0][0];
int[][] res = new int[m][n];
for(int i =0; i < m; i++)
res[i] = Arrays.copyOfRange(
original, i * n, i * n + n
);

return res;
}
}

AlgoXploration
visit shbcf.ru