如何使用java查找数组中相似元素的位置
假设我有一个数组:如何使用java查找数组中相似元素的位置,java,arrays,Java,Arrays,假设我有一个数组: input[] = {1,2,3,2,2,3,1,3,2} 我想找到这个数组中每个不同元素的所有位置,并将它们存储在新数组中。输出应如下所示: output_1[] = {0,6} //Position of "1" in input array output_2[] = {1,3,4,8} //Position of "2" in input array output_3[] = {2,5,7} //Position of "3" in input array 该代码应
input[] = {1,2,3,2,2,3,1,3,2}
我想找到这个数组中每个不同元素的所有位置,并将它们存储在新数组中。输出应如下所示:
output_1[] = {0,6} //Position of "1" in input array
output_2[] = {1,3,4,8} //Position of "2" in input array
output_3[] = {2,5,7} //Position of "3" in input array
该代码应适用于具有任意大小和任意数量不同元素的数组。以下代码将使用输入数组中任何不同值的位置填充
映射。由于映射
不能包含重复的键,因此它对于存储相似元素的所有位置非常有用。您可以看到,我检查映射
是否已经包含给定值的键,如果已经包含,我将其位置添加到现有的列表
。如果没有,我将创建一个新的列表
,其中值的位置作为初始值
import java.util.*;
public class Sandbox {
private Map<Integer, List<Integer>> positions;
private int[] input;
public static void main(String[] args) {
(new Sandbox()).run();
}
public Sandbox() {
positions = new HashMap<Integer, List<Integer>>();
input = new int[] { 1,2,3,2,2,3,1,3,2 };
}
private void run() {
for(int i = 0; i < input.length; i++) {
Integer value = input[i];
if(positions.containsKey(value)) {
List<Integer> list = positions.get(value);
list.add(i);
} else {
List<Integer> list = new ArrayList<Integer>();
list.add(i);
positions.put(value, list);
}
}
for(Integer key : positions.keySet()) {
System.out.println("Value: " + key);
System.out.println("----------");
for(Integer position : positions.get(key)) {
System.out.println("Position: " + position);
}
System.out.println();
}
}
}
到目前为止,你做了什么?@Averroes我已经确定了唯一元素。就像java中任何给定数组的1,2,3。但是我不知道如何在唯一元素的数量不断变化的情况下找到所有唯一元素的位置。它起作用了。我确信我能用它解决我的问题…这是一个非常好的方法解决方案
Value: 1
----------
Position: 0
Position: 6
Value: 2
----------
Position: 1
Position: 3
Position: 4
Position: 8
Value: 3
----------
Position: 2
Position: 5
Position: 7
package com.loknath.lab;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
int input[] = { 1, 2, 3, 2, 2, 3, 1, 3, 2 };
Set<Integer> set = new HashSet<Integer>();
for (Integer integer : input) {
set.add(integer);
}
for (Integer integer : set) {
findIndexes(integer, input);
}
}
public static void findIndexes(Integer integer, int[] input) {
System.out.print("output_" + integer + "[]= {");
for (int i = 0; i < input.length; i++) {
if (input[i] == integer) {
System.out.print(i + ",");
}
}
System.out.print("}");
System.out.println();
}
}
output_1[]= {0,6,}
output_2[]= {1,3,4,8,}
output_3[]= {2,5,7,}