检查int数组中是否存在int的另一个示例

vpfxa7rd  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(317)

假设我有一个名为sequence的int数组 [1, 3, 2, 4, 3, 5, 4, 6, 1, 3] 我想看看 1 存在于数组中的第一个之外,如果存在,我想在数组中获取它的索引。
到目前为止,我已经做到了:

// Get the first and second number of the sequence array
int firstNumberIndex = 0;
int firstNumber = sequence[0];
int secondNumber = sequence[1];
// Check that firstNumber < secondNumber
if (firstNumber < secondNumber) {
    // Remove firstNumber from the sequence array
    instance = removeElement(sequence, firstNumberIndex);
    // Check whether another instance of firstNumber exists in sequence array
    if (contains(sequence, firstNumber)) {
        // Here, I would like to get the index of the other instance of '1', for example

    }
}
slsn1g29

slsn1g291#

与原始执行速度相比,更倾向于可读性:

List<Integer> list = new ArrayList<>();
IntStream.of(sequence).forEach(list::add);
int index = list.subList(1, list.size()).indexOf(sequence[0]) + 1;

观看现场演示。 index0 如果不存在第二次出现。

gt0wga4j

gt0wga4j2#

快速回答使用哈希:

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

public class Snippet {

    public static void main(String[] args) {
        int [] sequence = {1, 3, 2, 4, 3, 5, 4, 6, 1, 3};
        Map<Integer,List<Integer>> indexMap = new LinkedHashMap<>();
        for (int i=0 ; i < sequence.length ; i++) {
          int val = sequence[i];
          indexMap.computeIfAbsent(val,k->new ArrayList<>()).add(i);
        }
        System.out.println(indexMap);
    }

}

输出: {1=[0, 8], 3=[1, 4, 9], 2=[2], 4=[3, 6], 5=[5], 6=[7]} 所以它为序列中的每一个值都给出了找到这个值的所有索引,这些索引可能大于或不大于op所要求的值。
这些值按遇到的顺序返回(感谢linkedhashmap),并对索引进行排序。总的来说,它在时间上是o(序列长度)。

相关问题