# 算法题：数组去重进阶版——JavaScript及Java实现

``````const union = [
{ id: 1, w: 1 },
{ id: 2, w: 4 },
{ id: 1, w: 2 },
{ id: 2, w: 6 }
]``````

## JavaScript 实现

``````function removeDuplicateElements(arr) {
let map = new Map();
let res = [];
for (let i=0; i<arr.length; i++) {
let cached = map.get(arr[i].id);
if (!cached || (cached < arr[i].w)) {
// 如果键值不存在
// 或者已有的w小于当前遍历的w
map.set(arr[i].id, arr[i].w);
}
}
for (let [key, value] of map) {
res.push({
id: key,
w: value
})
}
return res
}``````

## Java 实现

``````package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RemoveDuplicateElements {
public Map<String, Integer> getElement(int id, int w) {
return Map.of("id",id, "w",w);
}
public List<Map<String, Integer>> getTestCase() {
List<Map<String, Integer>> list = new ArrayList<>();
int[] idList = {1,2,1,2}, wList = {1,4,2,6};
for (int i=0; i<4; i++) {
}
return list;
}
public static void main(String[] args) {
RemoveDuplicateElements removeDuplicateElements = new RemoveDuplicateElements();
List<Map<String, Integer>> testCase = removeDuplicateElements.getTestCase();
System.out.println(testCase);
}
}``````

18 声望
2 粉丝
0 条评论