gpt4 book ai didi

java - 返回数组中重复数的最小索引值

转载 作者:行者123 更新时间:2023-11-30 08:01:28 24 4
gpt4 key购买 nike

我有一个 Integer 数组,我想从中返回出现的最小数字的索引值。

Integer[] array = {8,2,10,7,2,10}; 

因此,在这种情况下,如果我查找数字 2,我发现 2 包含在 array[1]array[4] 中。我在管理数组方面有点迷茫。

到目前为止我所做的是检查给定的数字是否存在

public int exist( Integer number  ) {
int index = 0;
int position = 0;
while (position <= array.length && number == array[position]){
index = index + 1;
if( index <= array.length ){
index = position ;
} else {
index = -1;
}
}
return index ;
}

我从互联网上找到了这段代码,它找到了整数数组中的第一个重复元素

class Main {
// This function prints the first repeating element in arr[]
static void printFirstRepeating(int arr[]) {
// Initialize index of first repeating element
int min = -1;

// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();

// Traverse the input array from right to left
for (int i=arr.length-1; i>=0; i--) {
// If element is already in hash set, update min
if (set.contains(arr[i]))
min = i;
else // Else add element to hash set
set.add(arr[i]);
}
// Print the result
if (min != -1)
System.out.println("The first repeating element is " + arr[min]);
else
System.out.println("There are no repeating elements");
}

// Driver method to test above method
public static void main (String[] args) throws java.lang.Exception {
int arr[] = {10, 5, 3, 4, 3, 5, 6};
printFirstRepeating(arr); // output 5
}
}

我仍然无法将此代码与第一个代码结合起来以获得我真正想要的东西。

最佳答案

解决此问题的一种方法是使用 Map而不是 HashSet .

制作 Map<Integer,Integer>它将数组中的值映射到该数字的第一次出现。遍历数组,如果值已经存在,则检查映射。

  • 如果key不在map中,则将当前索引插入map
  • 如果key在map中,则返回map中对应的value。

搜索代码如下所示:

Map<Integer,Integer> firstAppearance = new HashMap<>();
for (int i = 0 ; i != arr.length ; i++) {
if (firstAppearance.containsKey(arr[i])) {
return firstAppearance.get(arr[i]);
} else {
firstAppearance.put(arr[i], i);
}
}

关于java - 返回数组中重复数的最小索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com