我是Java新手,我正在进行数组排序问题,我遇到了这个问题的困难。搜索了simmular或重复的帖子,但似乎没有找到任何。
问题是“找到数组中最相同的相邻元素并将它们写入新数组”。
我的问题是。 如何将来自另一个数组的大多数相邻元素存储在数组中?
这是我到目前为止所做的工作。
int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array
int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];
for (i=1; i<length; i++)
{
if (arr[i-1]==arr[i])
{
counter++; // Counter to represent maximal adjacent occurred elem.
resultArr[i] = arr[i] //Writing elements in result array
}
}
System.out.println(counter);
System.out.println(resultArr);
Input: It is the test array "arr"
Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )
我的输出是(直接来自控制台)
1
[I @ 6d06d69c
答案 0 :(得分:0)
你在代码中犯了两个错误,首先你对输入数组i
和结果数组arr
使用相同的索引resultArr
,你应该使用另一个错误resultArr
喜欢这个
int resultArrIndex = 0;
for (i=1; i<length; i++)
{
if (arr[i-1]==arr[i])
{
counter++; // Counter to represent maximal adjacent occurred elem.
resultArr[resultArrIndex] = arr[i] //Writing elements in result array
resultArrIndex++;
}
}
其次,这不是打印数组的方法,要么像这样在for
循环中执行
for (int i = 0; i < resultArr.length; i++) {
System.out.println(resultArr[i]); // will print each in a line
}
或者像这样
System.out.println(Arrays.toString(resultArr)); // Print all in one line
答案 1 :(得分:0)
Break the problem down, first a method to determine when runs of adjacent values stop;
private static int runsTo(int[] vals, int index) {
for (int i = index; i < vals.length - 1; i++) {
if (vals[i] != vals[i + 1]) {
return i;
}
}
return vals.length;
}
Then we can use that with Arrays.toString(int[])
1 以及Arrays.copyOfRange(int[], int, int)
喜欢
int[] arr = { 2, 1, 1, 3, 3, 2, 2, 2, 2, 1, 1 };
int index = 0, count = 0;
for (int i = 0; i < arr.length; i++) {
int r = runsTo(arr, i);
int c = r - i + 1;
if (c > count) {
index = i;
count = c;
i += count - 1;
}
}
System.out.println(Arrays.toString(arr));
System.out.printf("Starting from %d get %d%n", index, count);
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, index, index + count)));
哪个输出
[2, 1, 1, 3, 3, 2, 2, 2, 2, 1, 1]
Starting from 5 get 4
[2, 2, 2, 2]
1 Java数组不会覆盖toString()
,因此您将获得数组的哈希码。
答案 2 :(得分:0)
以下是您的解决方案:
package com.sujit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Test {
public static int count = 0;
public static void main(String[] args) {
Integer[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array
List<Integer> resultList =Arrays.asList(arr);
List<Integer> maxOccurence = new ArrayList<Integer>();
Set<Integer> set = new HashSet<>();
for (Integer integer : resultList) {
set.add(integer);
}
for (Integer integer : set) {
int freq = Collections.frequency(resultList, integer);
maxOccurence.add(freq);
System.out.println("Element : "+integer+" Occurences= "+freq);
}
System.out.println(Collections.max(maxOccurence));
}
}