【问题标题】:Check if another instance of int exists in an int array检查 int 数组中是否存在另一个 int 实例
【发布时间】:2021-07-17 02:31:41
【问题描述】:

假设我有一个名为 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
    }
}

【问题讨论】:

  • 1 是任意数字还是总是第一个元素?
  • @Bohemian 我想找到数组中第一个元素的另一个出现。在这种情况下,由于1 是第一个元素,我想找到它其他出现的索引

标签: java arrays search integer


【解决方案1】:

快速答案使用哈希:

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(序列的长度)。

【讨论】:

    【解决方案2】:
    1. 您可以使用List#indexOf 方法两次来获取List&lt;Integer&gt; 中对象的第二次出现:
      public static int getSecond(List<Integer> list, int val) {
          // index of the first occurrence
          int i = list.indexOf(val);
          // if found and not the last one
          if (i > -1 && i < list.size() - 1) {
              // index of the second occurrence from
              // the sublist after the first occurrence
              int j = list.subList(i + 1, list.size()).indexOf(val);
              // if found, return the composite index
              if (j > -1) return j + i + 1;
          }
          // not found
          return -1;
      }
      
      public static void main(String[] args) {
          List<Integer> list = Arrays.asList(1, 3, 2, 4, 3, 5, 4, 6, 1, 3);
          System.out.println(getSecond(list, 3)); // 4
          System.out.println(getSecond(list, 1)); // 8
          System.out.println(getSecond(list, 6)); // -1
          System.out.println(getSecond(list, 7)); // -1
      }
      
    2. 如果只需要数组int[],则可以使用IntStream
      public static int getSecond(int[] arr, int val) {
          return IntStream
                  // iterating over array indices
                  .range(0, arr.length)
                  // filter the search elements
                  .filter(i -> arr[i] == val)
                  // skip the first one
                  .skip(1)
                  // take the second one
                  .findFirst()
                  // if not found
                  .orElse(-1);
      }
      
      public static void main(String[] args) {
          int[] arr = {1, 3, 2, 4, 3, 5, 4, 6, 1, 3};
          System.out.println(getSecond(arr, 3)); // 4
          System.out.println(getSecond(arr, 1)); // 8
          System.out.println(getSecond(arr, 6)); // -1
          System.out.println(getSecond(arr, 7)); // -1
      }
      

    【讨论】:

      【解决方案3】:

      比原始执行速度更喜欢可读性:

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

      live demo

      如果不存在第二个匹配项,index 将是 0

      【讨论】:

        猜你喜欢
        • 2016-05-28
        • 2021-04-03
        • 2018-01-13
        • 1970-01-01
        • 2021-05-15
        • 2012-08-14
        • 2020-05-20
        • 2015-01-16
        • 1970-01-01
        相关资源
        最近更新 更多