假设(new Integer[]{10,10,20,10,20,30,10,20,30,40,50,10,20,30,40,50,60})
传递给方法public static <T> Pair<T, Integer> mode(T items[])
。该方法应返回10, 5
(数组中有五个数字10).S,基本上该方法返回数组中最常用的元素。我该如何完成这种方法?请不要MAPS
,COLLECTIONS
,HashSets
,仅ArrayLists
。
import java.util.ArrayList;
public class Mode {
public static <T> Pair<T, Integer> mode(T items[])
{
ArrayList <Pair<T, Integer>> temp = new ArrayList<>();
//ArrayList <T> temp = new ArrayList<>();
for(T values: items)
{
temp.add((Pair<T, Integer>) values);
}
for(int i = 0; i < temp.size(); i++)
for(int j = 0; j < temp.size(); j++)
{
if(temp.get(i) == temp.get(j))
}
}
}
public class Pair<X,Y>{
private X first;
private Y second;
public Pair(X x, Y y){
this.first = x;
this.second = y;
}
public X getFirst(){
return this.first;
}
public Y getSecond(){
return this.second;
}
public boolean equals(Object o){
if(!(o instanceof Pair)){
return false;
}
Pair p = (Pair) o;
return
this.first.equals(p.first) &&
this.second.equals(p.second);
}
public String toString(){
return String.format("(%s,%s)",first,second);
}
}
答案 0 :(得分:0)
import java.util.ArrayList;
public class Mode {
public static Pair<T, Integer> mode(T[] a)
{
int count = 1, tempCount;
T popular = a[0];
T temp;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 1;
for (int j = 1; j < a.length; j++)
{
if (temp.equals(a[j]))
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return new Pair(popular, new Integer(count));
}
}
public class Pair<X,Y>{
private X first;
private Y second;
public Pair(X x, Y y){
this.first = x;
this.second = y;
}
public X getFirst(){
return this.first;
}
public Y getSecond(){
return this.second;
}
public boolean equals(Object o){
if(!(o instanceof Pair)){
return false;
}
Pair p = (Pair) o;
return
this.first.equals(p.first) &&
this.second.equals(p.second);
}
public String toString(){
return String.format("(%s,%s)",first,second);
}
}
如果您有任何疑问,请与我们联系。