本文讲述了通过JAVA解决 AI刷题 470.珠子颜色去重
470.珠子颜色去重
问题描述:
小S拥有一条由n颗珠子组成的手链,每颗珠子都有一个对应的颜色编号。她希望将手链上相同颜色的珠子进行去重,只保留每种颜色最后出现的那颗珠子,同时保持珠子原来的相对顺序。
例如,如果珠子的颜色编号是 [1, 2, 1, 3, 4, 2, 4, 4],去重后的珠子颜色应该是 [1, 3, 2, 4]。
题目要求:
题目所给的函数声明为:public static int[] solution(int n, int[] a),即该函数接收int类型的数组长度n,以及对应的数组a[]。返回结果为int类型的数组,表示去重之后珠子的颜色编号数组。
题目样例:
样例1:
输入:
n = 8 ,a = [1, 2, 1, 3, 4, 2, 4, 4]
输出:[1, 3, 2, 4]
样例2:
输入:
n = 5 ,a = [5, 5, 5, 5, 5]
输出:[5]
样例3:
输入:
n = 6 ,a = [6, 1, 2, 6, 1, 2]
输出:[6, 1, 2]
解析:
保存最后的颜色编号:
为了保存同种颜色最后的编号,必须要使用一种不能保存相同内容的数据结构,同时要使插入不同种颜色的顺序不被打乱。恰好JAVA中存在一种数据结构可以满足我们的需要,那就是LinkedHashMap。LinkedHashMap 是 Java 中的一个类,它是 java.util 包的一部分。LinkedHashMap 继承自 HashMap,因此它具有哈希表的快速访问特性,并且保留了插入顺序或访问顺序。同时它通过键值对保存数据,当键相同时,值会被覆盖,刚好可以通过该特性得到最后的编号。
因此可以写出如下代码:
Map<Integer, Integer> lastSeen = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
lastSeen.put(a[i], i);
}
用来保存所有颜色最后出现的编号。
整理为数组
为了将最后的数据放到数组里,首先需要通过可变数组将颜色一点点的添加到一种数据里面,在这里可以用ArrayList来不断添加元素。通过判断当前颜色所对应的下标是否为所在颜色的最后编号,来决定是否添加到ArrayList中。可以写出代码:
List<Integer> dedupedList = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (lastSeen.get(a[i]) == i) {
dedupedList.add(a[i]);
}
}
通过上述方法,得到了去重后的珠子颜色的ArrayList类型的变量。再通过一些操作,通过ArrayList类型得到int类型的数组。代码为:
int[] dedupedArray = new int[dedupedList.size()];
for (int i = 0; i < dedupedList.size(); i++) {
dedupedArray[i] = dedupedList.get(i);
}
最终得到了保存去重后珠子颜色的int类型数组。
具体代码:
结合上述内容,得到的最终代码为:
public static int[] solution(int n, int[] a) {
Map<Integer, Integer> lastSeen = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
lastSeen.put(a[i], i);
}
List<Integer> dedupedList = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (lastSeen.get(a[i]) == i) {
dedupedList.add(a[i]);
}
}
int[] dedupedArray = new int[dedupedList.size()];
for (int i = 0; i < dedupedList.size(); i++) {
dedupedArray[i] = dedupedList.get(i);
}
return dedupedArray;
}