【发布时间】:2021-11-19 13:55:50
【问题描述】:
我的任务是编写一个方法,该方法从指定的 int 数组中返回一个数字列表,这些数字在该数组中出现 n 次或多次。
例如 findNumbersWithCount(new int[] {5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5 }, 2) 应该找到指定数组中出现 2 次或更多次的所有数字并返回它们的列表,即这个示例调用应该返回一个带有数字 [2,3,4,5]。 也就是说在这个示例数组中,元素 1 出现了一次,2 出现了两次,3 出现了 3 次, 4 四次和 5 五次,使出现两次或多次的元素成为 2、3、4 和 5。 下面是我写的代码:
public class Problem{
public static List<Integer> findNumbersWithCount(int[] listOfNumbers, int countOfOccurrenceThreshold) {
int count = 0;
int [] arr = new int [listOfNumbers.length];
int visited = -1;
for (int i = 0; i < listOfNumbers.length; i++){
for (int j = i + 1; j < listOfNumbers.length; j++){
if (listOfNumbers[i] == listOfNumbers[j]){
count++;
arr[j] = visited;
}
}
if (arr[i] != visited){
arr[i] = count;
}
}
//calling the generic function that converts Array into List
List<Integer> list = ArrayToListConversion(arr);
return list;
}
public static <T> List<T> ArrayToListConversion(int[] array) {
//creating the constructor of the List class
List<Integer> list = new ArrayList<>();
//using for-each loop to iterate over the array
for (int t : array) {
//adding each element to the List
list.add(t);
}
//returns the list converted into Array
return (List<T>) list;
}
public static void main(String[] args){
try {
List<Integer> x = findNumbersWithCount(new int[] { 5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5 }, 2);
System.out.println(x);
}
catch (UnsupportedOperationException ex){
System.out.println("Waiting to be implemented.");
}
}
}
我有这个列表 [4, 7, 9, 10, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]而不是 [2,3,4,5]。有人可以帮忙解决这个问题吗?
【问题讨论】:
-
一个(但可能不是唯一的)错误:您没有在用于计算找到数字的频率的循环之间重置计数器。