
Sponsored
Sponsored
Explanation: Iterator Filtering
This approach involves iterating through each record (or row) in the DataFrame and checking the 'student_id' against the specified value (101). Once a match is found, we can extract the 'name' and 'age' and return it as the result.
Time Complexity: O(n), where n is the number of students. We may have to check each student in the worst case.
Space Complexity: O(1), as no additional space beyond input storage is used.
1#include <vector>
#include <string>
struct Student {
int student_id;
std::string name;
int age;
};
void findStudent(const std::vector<Student>& students) {
for (const auto& student : students) {
if (student.student_id == 101) {
std::cout << "+---------+-----+\n";
std::cout << "| " << student.name << " | " << student.age << " |\n";
std::cout << "+---------+-----+\n";
break;
}
}
}
int main() {
std::vector<Student> students = {
{101, "Ulysses", 13},
{53, "William", 10},
{128, "Henry", 6},
{3, "Henry", 11}
};
findStudent(students);
return 0;
}In C++, we use a struct to define the Student type, and a vector to hold all student records. The findStudent() function iterates through the vector to find the target student ID, then prints out the 'name' and 'age'.
Explanation: Lookup with Map/Dictionary
This approach involves using a hash table, such as a Dictionary in Python or HashMap in Java, to store each student record with their student_id as the key. This enables direct access to a record based on student_id with average O(1) complexity, extracting 'name' and 'age' immediately.
Time Complexity: O(1), as hash table operations (get) average constant time.
Space Complexity: O(n), space usage increases with input size.
1import java.util.HashMap;
2
3class Student {
4 String name;
5 int age;
6
7 Student(String name, int age) {
8 this.name = name;
9 this.age = age;
10 }
11}
12
13public class SelectData {
14 public static void main(String[] args) {
15 HashMap<Integer, Student> studentMap = new HashMap<>();
16 studentMap.put(101, new Student("Ulysses", 13));
17 studentMap.put(53, new Student("William", 10));
18 studentMap.put(128, new Student("Henry", 6));
19 studentMap.put(3, new Student("Henry", 11));
20
21 Student student = studentMap.get(101);
22 if (student != null) {
23 System.out.println("+---------+-----+");
24 System.out.println("| " + student.name + " | " + student.age + " |");
25 System.out.println("+---------+-----+");
26 }
27 }
28}Using a HashMap, students are stored with their ID as keys. By accessing studentMap.get(101), we retrieve the record instantly, allowing the program to directly print out the 'name' and 'age'.