LeetCode 2877: Create a DataFrame from List
Problem Description
Explanation:
To create a DataFrame from a 2D list called student_data
, we need to iterate over the list and extract the student ID and age for each student. We can then format this data into a tabular form with columns for student_id and age.
Algorithm:
- Create an empty DataFrame.
- For each row in
student_data
, extract the student ID and age. - Add these values to the DataFrame under the corresponding columns.
- Display the DataFrame in the required format.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the number of rows in the student_data
list.
Space Complexity:
The space complexity is also O(n) since we are storing the data in a DataFrame.
:
Solutions
import java.util.List;
import java.util.ArrayList;
public class Solution {
public DataFrame createDataFrame(List<List<Integer>> student_data) {
DataFrame df = new DataFrame();
df.addColumn("student_id");
df.addColumn("age");
for (List<Integer> row : student_data) {
df.addRow(row.get(0), row.get(1));
}
return df;
}
static class DataFrame {
List<String> columns;
List<List<Integer>> data;
public DataFrame() {
columns = new ArrayList<>();
data = new ArrayList<>();
}
public void addColumn(String columnName) {
columns.add(columnName);
}
public void addRow(int student_id, int age) {
List<Integer> row = new ArrayList<>();
row.add(student_id);
row.add(age);
data.add(row);
}
public void display() {
System.out.println("+------------+-----+");
System.out.println("| student_id | age |");
System.out.println("+------------+-----+");
for (List<Integer> row : data) {
System.out.printf("| %-11d | %-3d |\n", row.get(0), row.get(1));
}
System.out.println("+------------+-----+");
}
}
}
Loading editor...