【问题标题】:How to find the nearest value from array?如何从数组中找到最接近的值?
【发布时间】:2018-02-23 22:07:31
【问题描述】:
public class A6{
    public static void main(String[] args){
        String personInfo[][]={ 
                {"Anderson",  "Varejao",     "1125"},
                {"Giorgi",  "Tevzadze",      "1125"},
                {"Will",      "Cherry",      "1225"},
                {"Kevin",     "Love",        "2525"},
                {"Kyrie",     "Livings",      "454"},
                {"Dion",      "Malborg",    "6250" } 
        };

        //max - who has the highest salary
        if(args[0].equals("max")){
            int max = Integer.parseInt(personInfo[0][2]);

            for(int i = 0; i < personInfo.length; i++) {
                int l = Integer.parseInt(personInfo[i][2]);        
                if(max < l){
                    max = l;
                }
             }

            for(int i = 0; i < personInfo.length; i++) {
                if(max == Integer.parseInt(personInfo[i][2])){
                     System.out.println(personInfo[i][0]);
                }
            }
            System.out.println("His sallary is:" +max );


        //  va ZZZ        - who has the closest salary to value ZZ
        if(args[0].equals("va")){
            for(int iž0; i < personInfo.length; i++{

            int l = Integer.parseInt(personInfo[i][2]);
            ...

        }
    }
}

我已经编写了一个方法来查找薪水最高的人,现在我正在尝试找出与我输入的值最接近的人。例如:我输入命令行 java A6 456 并且应该从命令行 Kyrie Livings 得到答案。我已经开始通过编写一个 for 循环并将字符串值从 personInfo 转换为 int 来执行此操作。有什么建议吗?

【问题讨论】:

  • 有内存限制吗?
  • 您可以创建一个循环遍历所有内容并计算“距离”并搜索最小值
  • 您可以执行与max 相同的操作,但不是检查最大值,而是检查min abs(diff)。这是输入的数字与工资之间的差值的最小绝对值。
  • 我的建议:1. 正确缩进你的代码。不仅为我们,也为您。如果格式正确,则阅读您自己的代码并对其进行调试会更容易。 2. 使用具有命名属性的类 Person,使用适当的类型来表示一个人。不是字符串数组。 person.getSalary()Integer.parseInt(person[2]) 简单得多。

标签: java algorithm for-loop


【解决方案1】:

试试这个:(考虑到内存使用没有限制):

int index = 0, minDiff = 0, diff = 0;

for(int i = 0;i<personInfo.length;i++){
    diff = Math.abs(personInfo[i][2] - inputVal);
    if(diff<minDiff){
        minDiff = diff;
        index = i;
    }        

}
return personInfo[index][2];

inputVal 是您将传递给此函数的参数,您要为其查找最近的薪水。您可以修改此逻辑以满足您对此用例的需求。

【讨论】:

  • 请修复diff变量的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
相关资源
最近更新 更多