题解 | 集合

集合

https://www.nowcoder.com/practice/635ff765d4af45b5bf8e3756ed415792

解题思路

这是一个集合合并问题。关键点:

  1. 数据结构选择

    • 使用 去重
    • 或使用排序后合并
  2. 输出要求

    • 升序输出
    • 元素间用空格分隔
    • 行末无空格

代码

#include <iostream>
#include <set>
using namespace std;

int main() {
    int n, m;
    while(cin >> n >> m) {
        set<int> s;
        
        // Input set A
        for(int i = 0; i < n; i++) {
            int x;
            cin >> x;
            s.insert(x);
        }
        
        // Input set B
        for(int i = 0; i < m; i++) {
            int x;
            cin >> x;
            s.insert(x);
        }
        
        // Output
        auto it = s.begin();
        cout << *it;
        ++it;
        for(; it != s.end(); ++it) {
            cout << " " << *it;
        }
        cout << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            
            TreeSet<Integer> set = new TreeSet<>();
            
            // Input set A
            for(int i = 0; i < n; i++) {
                set.add(sc.nextInt());
            }
            
            // Input set B
            for(int i = 0; i < m; i++) {
                set.add(sc.nextInt());
            }
            
            // Output
            Iterator<Integer> it = set.iterator();
            System.out.print(it.next());
            while(it.hasNext()) {
                System.out.print(" " + it.next());
            }
            System.out.println();
        }
    }
}
while True:
    try:
        n, m = map(int, input().split())
        # Input both sets and convert to set for uniqueness
        A = set(map(int, input().split()))
        B = set(map(int, input().split()))
        
        # Merge and sort
        result = sorted(A.union(B))
        
        # Output with proper formatting
        print(" ".join(map(str, result)))
        
    except:
        break

算法及复杂度

  • 算法:集合操作
  • 时间复杂度:,主要是排序的复杂度
  • 空间复杂度:,存储合并后的集合
全部评论

相关推荐

01-04 07:53
门头沟学院 C++
心愿便利贴:工作了以后回头再看待这个问题,从客观的视角来讲是因为每个人对自己的要求不同,学习好的人对自己的要求很高,所以觉得考不好就天塌了,认为自己学习好并且值得一份好工作的人也是一样,找不到符合自己预期的工作肯定也会觉得是侮辱,牛客上有很多名校大学生,肯定会存在这种好学生心态啊,“做题区”从来都不是贬义词,这是大部分普通人赖以生存的路径,这个有什么好嘲讽的,有“好学生心态”没有错,但是不要给自己太大的压力了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务