Implement the backend side of a user management page.
Given two user lists, one is the current database and the other is a list of possible changes. The first value in a change record is its user ID. If this value is 0, it is a new user to insert into the database. If the value is greater than 0, it is a user ID. Compare all of the user’s attributes with what is in the database. If there is any difference, update the record.
The implementation should return two lists. The first is a list of records to update. The second is a list of records to insert. The provided code will print the lengths of these lists.
Example
List 1 (Current Users in DB)
1 User1
2 User2
List 2 (Users List from UI)
1 User4
0 User5
2 User2
User ID 1 changes the username from User1 to User4. In the second line, the user ID is 0. A new user is created with the username User5. User ID 2 matches what is in the database, so no changes are made.
Return two lists: [1 User1] and [0 User5].
Function Description
Implement the CompareUsers function as described.
CompareUsers has the following parameters:
List<User> usersListInDB: the current databaseList<User> newUsersList: the new transactions
Return:
List<User>[]:[updated, inserted]
这道题考察的是“用户变更对比”逻辑:把数据库中的现有用户列表与前端提交的变更列表逐条匹配。若记录的 ID 大于 0,就按 ID 在数据库中查找对应用户,并逐个比较字段;只要有任意属性不同,就把该记录加入更新列表。若 ID 为 0,则表示这是新用户,需要加入插入列表。实现时最关键的是先建立一个按用户 ID 索引的映射,这样可以把查找从线性扫描降到常数时间,整体复杂度更稳定,适合处理较大的用户列表。