我完全被难住了。我休息了几个小时,但我似乎想不通这件事。这太让人心烦了!
我知道我需要检查数组中的当前元素,看看它是否出现在数组中的其他地方。我们的想法是输出以下内容:
用户被要求输入10个整数,这些整数被分配给一个数组(因此"numbers“作为该方法的参数)。假设我输入"1,1,2,3,3,4,5,6,7,8“。打印结果应为"1出现2次,2出现1次,3出现2次,4出现1次,5出现1次,6出现1次,7出现1次,8出现1次。“此打印将在单独的方法中完成。
我的代码中的所有内容都可以正常工作,除了我创建的这个用于计算出现次数的方法。
public static int getOccurrences(int[] numbers)
{
int count = 0;
for (int i = 0; i < numbers.length; i++)
{
int currentInt = numbers[i];;
if (currentInt == numbers[i])
{
count++;
}
}
return count;
}
我知道问题出在哪里了。我将数组中的当前整数元素设置为变量currentInt。if语句对数组中的每个整数元素进行计数,因此输出为"[I@2503dbd3发生10次“。
如何跟踪数组中每个元素的出现情况?
发布于 2015-04-14 10:50:27
@NYB你几乎是对的,但你必须输出计数值,并在每个元素检查时从零开始。
int count=0,currentInt=0;
for (int i = 0; i < numbers.length; i++)
{
currentInt = numbers[i];
count=0;
for (int j = 0; j < numbers.length; j++)
{
if (currentInt == numbers[j])
{
count++;
}
}
System.out.println(count);
}
@loikkk我对你的代码做了一些调整,以便打印出每个元素的匹配项。
int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };
Arrays.sort(a);
int nbOccurences = 1;
for (int i = 0, length = a.length; i < length; i++) {
if (i < length - 1) {
if (a[i] == a[i + 1]) {
nbOccurences++;
}
} else {
System.out.println(a[i] + " occurs " + nbOccurences
+ " time(s)"); //end of array
}
if (i < length - 1 && a[i] != a[i + 1]) {
System.out.println(a[i] + " occurs " + nbOccurences
+ " time(s)"); //moving to new element in array
nbOccurences = 1;
}
}
发布于 2015-04-14 10:43:46
你可以找到你的问题的答案here
我在示例中使用了Arrays.sort()
方法:
public class MyTest {
/**
* @param args
*/
public static void main(String[] args) {
int[] a = {1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1};
Arrays.sort(a);
int nbOccurences = 0;
for (int i = 0, length = a.length - 1; i < length; i++) {
if (a[i] == a[i + 1]) {
nbOccurences++;
}
}
System.out.println("Number same occurences : " + nbOccurences);
}
}
发布于 2019-02-04 14:05:56
最有效的方法是在迭代数组时创建hashmap来保存元素的出现。它将在2n时间复杂度内完成,这对这个问题来说是最好的-
HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
int count;
for(int i=0;i<arr.length;i++){
if(hmap.get(arr[i])==null){
hmap.put(arr[i],1);
}else{
count=hmap.get(arr[i]);
count++;
hmap.put(arr[i],count);
}
}
https://stackoverflow.com/questions/29618205
复制相似问题