PAT-BASIC1004——成绩排名

我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC

原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805321640296448

题目描述:

PAT-BASIC1004——成绩排名

知识点:结构体

思路:用C++的结构体或者Java的类存储数据

时间复杂度是O(n),其中n为输入的记录数。对于空间复杂度,如果存储了所有的记录值,那就是O(n)。如果只存储最大分数和最小分数的记录值,那就是O(1)。

C++代码:

#include<iostream>
#include<string>

using namespace std;

struct Student {
	string name;
	string number;
	int score;
};

int main() {
	int count;
	cin >> count;

	string name;
	string number;
	int score;
	cin >> name >> number >> score;

	Student lowestStudent;
	Student highestStudent;

	lowestStudent.name = name;
	lowestStudent.number = number;
	lowestStudent.score = score;

	highestStudent.name = name;
	highestStudent.number = number;
	highestStudent.score = score;

	for (int i = 1; i < count; i++) {
		cin >> name >> number >> score;
		if (score > highestStudent.score) {
			highestStudent.name = name;
			highestStudent.number = number;
			highestStudent.score = score;
		}
		if (score < lowestStudent.score) {
			lowestStudent.name = name;
			lowestStudent.number = number;
			lowestStudent.score = score;
		}
	}

	cout << highestStudent.name << " " << highestStudent.number << endl;
	cout << lowestStudent.name << " " << lowestStudent.number << endl;
}

C++解题报告:

PAT-BASIC1004——成绩排名

JAVA代码:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = scanner.nextInt();
        scanner.nextLine();
        ArrayList<Student> arrayList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            String[] messages = scanner.nextLine().split(" ");
            arrayList.add(new Student(messages[0], messages[1], Integer.parseInt(messages[2])));
        }
        Student maxScoreStudent = arrayList.get(0);
        Student minScoreStudent = arrayList.get(0);
        for (int i = 1; i < count; i++) {
            if(maxScoreStudent.score < arrayList.get(i).score){
                maxScoreStudent = arrayList.get(i);
            }
            if(minScoreStudent.score > arrayList.get(i).score){
                minScoreStudent = arrayList.get(i);
            }
        }
        System.out.println(maxScoreStudent.name + " " + maxScoreStudent.number);
        System.out.println(minScoreStudent.name + " " + minScoreStudent.number);
    }
}

class Student{
    public String name;
    public String number;
    public Integer score;

    public Student(String name, String number, Integer score){
        this.name = name;
        this.number = number;
        this.score = score;
    }
}

JAVA解题报告:

PAT-BASIC1004——成绩排名