Java 在数组中查找模式
此代码只能在存在单一模式时获取模式。我想知道当存在两种模式时如何返回-1。例如:1 1 2 2 3。当没有模式存在时返回-1,123456Java 在数组中查找模式,java,arrays,Java,Arrays,此代码只能在存在单一模式时获取模式。我想知道当存在两种模式时如何返回-1。例如:1 1 2 2 3。当没有模式存在时返回-1,123456 public Long getMode() { long [] num = this.getElements(); long maxValue=0, maxCount=0; for (int i = 0; i < num.length; ++i){ long count = 0;
public Long getMode() {
long [] num = this.getElements();
long maxValue=0, maxCount=0;
for (int i = 0; i < num.length; ++i){
long count = 0;
for (int j = 0; j < num.length; ++j){
if (num[j] == num[i])
++count;
}
if (count > maxCount){
maxCount = count;
maxValue = num[i];
}
}
return maxValue;
}
public Long getMode(){
long[]num=this.getElements();
长maxValue=0,maxCount=0;
对于(int i=0;i最大计数){
最大计数=计数;
maxValue=num[i];
}
}
返回最大值;
}
您的代码工作正常,但如果没有模式或存在两种模式,则不返回-1
为此,您可以按如下方式更改程序:(我已经列出了我更改的部分)
公共静态长getMode(){
long[]num=this.getElements();
长maxValue=0,maxCount=0;
boolean err=false;//用于检查是否存在错误的新vraible。
对于(int i=0;i最大计数){
最大计数=计数;
maxValue=num[i];
err=false;//如果找到有效模式,则将err设置为false。
}
系统输出打印项次(错误);
}
返回err?-1:maxValue;//如果err为false,则返回值,否则返回-1
}
您可以将计数存储在int[10]
数组中,而不是用一个值来保存值,而每个元素都表示一个数字的出现。最后,您只需在数组中找到最大值,如果它出现两次或两次以上,您只需返回-1
public static Long getMode() {
long [] num = this.getElements();
long maxValue=0, maxCount=0;
boolean err = false; // New vraible to check if there is an error.
for (int i = 0; i < num.length; ++i){
long count = 0;
for (int j = 0; j < num.length; ++j){
if (num[j] == num[i])
++count;
}
if(count==maxCount && maxValue!=num[i]){ // if there are two modes
err=true; // then set err to true.
}else if (count > maxCount){
maxCount = count;
maxValue = num[i];
err = false; // If valid mode is found, then set err to false.
}
System.out.println(err);
}
return err ? -1 : maxValue; // return value if err is false, else return -1
}