gpt4 book ai didi

java - 如何获取数组中最常见的字符?

转载 作者:行者123 更新时间:2023-11-30 05:53:32 25 4
gpt4 key购买 nike

假设我有一个这样的整数数组:{5,3,5,4,2}

我有一个返回最常见字符的方法

public int highestnumber(String[] num) {

int current_number = Integer.parseInt(num[0]);
int counter = 0;
for (int i = 1; i < num.length; ++i) {
if (current_number == Integer.parseInt(num[i])) {
++counter;

} else if (counter == 0) {
current_number = Integer.parseInt(num[i]);
++counter;

} else {
--counter;

}
}

return current_number;
}

但是如果我有多个公共(public)字符,那么我需要获取最接近一个 (1) 的数字,就像我有一个这样的数组一样:{5,5,4,4,2};

那么该方法应该返回 4,我应该为此做什么?

最佳答案

根据我对你问题的理解,

你要做的是,

1. Create ArrayList from your int[]
2. Use HashMap for find duplicates, which one is unique
3. Sort it as Ascending order,
4. First element is what you want..

编辑:回答您的问题

int[] arr = {5, 4, 5, 4, 2};
ArrayList<Integer> resultArray = new ArrayList<Integer>();
Set<Integer> set = new HashSet<Integer>();

for (int i = 0; i < arr.length; i++)
{
if (set.contains(arr[i]))
{
System.out.println("Duplicate value found at index: " + i);
System.out.println("Duplicate value: " + arr[i]);
resultArray.add(arr[i]);
}
else
{
set.add(arr[i]);
}
}
Collections.sort(resultArray);

for (int i = 0; i < resultArray.size(); i++)
{
Log.e("Duplicate Values:", resultArray.get(i) + "");
}

您的需求是,

int values = resultArray.get(0);

关于java - 如何获取数组中最常见的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459216/

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