繁体   English   中英

如何使用Java查找数组中相似元素的位置

[英]How to find position of similar elements in array using java

假设我有一个数组:

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

该代码应适用于具有任何大小和任意数量的不同元素的数组。

下面的代码将在Map<Integer, List<Integer>>填充在输入Array中找到的任何不同值的位置。 由于Map不能包含重复的键,因此对于存储相似元素的所有位置很有用。 您可以看到我检查了Map已经包含给定值的Key,如果确实存在,则将其位置添加到现有List 如果没有,我将值的位置作为初始值创建一个新的List

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();
        }
    }
}

这将打印:

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,}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM