解题思路

  1. 这是一个会话列表管理问题,需要模拟即时聊天工具的会话排序逻辑
  2. 核心规则:
    • 新会话插入到列表最上方
    • 已存在的会话移动到最上方
    • 保持会话唯一性
  3. 实现步骤:
    • 使用数组存储会话ID
    • 对每个新会话ID,先检查是否存在
    • 如果存在,将其移到最上方
    • 如果不存在,插入到最上方

代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int T, N, temp;
    vector<int> chat;
    
    cin >> T;
    while(T--) {
        cin >> N;
        chat.clear();
        
        // 处理每个会话ID
        for(int i = 0; i < N; i++) {
            cin >> temp;
            
            // 查找是否存在
            auto it = find(chat.begin(), chat.end(), temp);
            if(it != chat.end()) {
                // 已存在,从原位置删除
                chat.erase(it);
            }
            // 插入到最上方
            chat.insert(chat.begin(), temp);
        }
        
        // 输出结果
        for(int i = 0; i < chat.size(); i++) {
            cout << chat[i];
            if(i < chat.size() - 1) cout << " ";
        }
        cout << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        
        while(T-- > 0) {
            int N = sc.nextInt();
            ArrayList<Integer> chat = new ArrayList<>();
            
            // 处理每个会话ID
            for(int i = 0; i < N; i++) {
                int temp = sc.nextInt();
                
                // 查找并删除已存在的会话
                chat.remove(Integer.valueOf(temp));
                // 插入到最上方
                chat.add(0, temp);
            }
            
            // 输出结果
            for(int i = 0; i < chat.size(); i++) {
                System.out.print(chat.get(i));
                if(i < chat.size() - 1) System.out.print(" ");
            }
            System.out.println();
        }
    }
}
def process_chat_list(N, chats):
    chat_list = []
    for chat_id in chats:
        # 如果会话已存在,先删除
        if chat_id in chat_list:
            chat_list.remove(chat_id)
        # 插入到最上方
        chat_list.insert(0, chat_id)
    return chat_list

T = int(input())
for _ in range(T):
    N = int(input())
    chats = list(map(int, input().split()))
    result = process_chat_list(N, chats)
    print(' '.join(map(str, result)))

算法及复杂度

  • 算法:数组操作
  • 时间复杂度: - 为测试用例数,每个会话可能需要 的查找和移动操作
  • 空间复杂度: - 需要存储会话列表