gpt4 book ai didi

java - 在数组中查找重复数字时出现问题,是我的技术不好吗?

转载 作者:行者123 更新时间:2023-12-01 19:29:16 26 4
gpt4 key购买 nike

我使用 HashMap 来存储每个元素的出现次数,然后迭代 HashMap 以获取重复的元素,但此解决方案感觉有些不对劲。

Firecode.io 中的问题陈述:

Write a method duplicate to find the repeated or duplicate elements in an array. This method should return a list of repeated integers in a string with the elements sorted in ascending order (as illustrated below).

duplicate({1,3,4,2,1}) --> "[1]"

duplicate({1,3,4,2,1,2,4}) --> "[1, 2, 4]"

Note: You may use toString() method to return the standard string representation of most data structures, and Arrays.sort() to sort your result.*

这是我的代码:

 public String duplicate(int[] numbers) {
HashMap < Integer, Integer > hs = new HashMap < Integer, Integer > ();
for (int i = 0; i < numbers.length; i++) {
if (hs.get(numbers[i]) == null) {
hs.put(numbers[i], 1);
} else hs.put(numbers[i], (Integer) hs.get(numbers[i]) + 1);
}

int size = 0;
for (int i: hs.keySet()) {
if (hs.get(i) > 1) {
size++;
}
}
int j = 0;
int[] a = new int[size];
for (int i: hs.keySet()) {
if (hs.get(i) > 1) {
a[j++] = i;
}
}

Arrays.sort(a);
return Arrays.toString(a);
}

最佳答案

这是我的做法:(出于教育目的的评论,可能不会在生产代码中包含它们。)

public String duplicate(int[] numbers) {

// holds the items we've encountered more than once.
// TreeSet<> keeps things in sorted order for us.
final SortedSet<Integer> duplicates = new TreeSet<>();

// keeps track of items we've encountered.
final Set<Integer> encountered = new HashSet<>();

// iterate over every number
for (final int number : numbers) {
// Add the item to encountered. Set.add() will return true if
// the element is new to the set.
if (!encountered.add(number)) {
// Since the element wasn't new, ensure this item exists in the duplicates collection.
duplicates.add(number);
}
}

return duplicates.toString();
}

关于java - 在数组中查找重复数字时出现问题,是我的技术不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304862/

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