找到一定数量后的最小数字:Comparable smallestAfter(Comparable [] value,Comparable after)

时间:2015-02-06 01:44:41

标签: java algorithm object

我正在尝试编写一个算法,在用户定义数字后找到最小的数字。说值= {4,2,1,3}。并且用户希望在2之后找到最小的,该程序将射出3。

任何线索或帮助什么放在最小的身体后? 谢谢。 以下是我到目前为止的情况:

public static Comparable smallest(Comparable[] values)
{
  Comparable smallestSoFar = values[0];
  for (int i = 1; i < values.length; i++)
     if (values[i].compareTo(smallestSoFar) < 0)
        smallestSoFar = values[i];
  return smallestSoFar;
}   
 public static Comparable smallestAfter(Comparable[] values, Comparable after)
 {   
        //After a few help, this is my algorithm I personally wrote.
             Comparable smallest = smallest(values);
             Comparable largest = smallest(values);
             for(int i = 1; i < values.length; i ++){
                  if(largest.compareTo(values[i]) < 0){
                   largest = values[i];
                }
          }


    for(int i = 1; i < values.length; i ++){
        if((values[i].compareTo(smallest) > 0) && (values[i].compareTo(after)       > 0) && (values[i].compareTo(largest) < 0))
            smallest = values[i];
    }
    return smallest;

  }

3 个答案:

答案 0 :(得分:0)

for each v in values {
    if (v < smallestSoFar AND v > after) {
        smallestSoFar = v;
    }
}

答案 1 :(得分:0)

您可以更改&lt;,&gt;与compareTo。如果没有大于'after'的数字,其他答案将无效,他们将只返回第一个元素而不是任何内容。

public static Comparable smallestAfter(Comparable[] values, Comparable after) {

 Comparable smallest = null;
 for (int i = 0; i < values.length; i++) {
     if (values[i] > after && (smallest == null || values[i] < smallest)) {
         smallest = values[i];
     }
 }
 return smallest;
}

答案 2 :(得分:0)

<强>逻辑:

遍历所有元素。

a) If the current element is smaller than first, then update smallest 
   and second smallest. 
b) Else if the current element is smaller than second and not the smallest element then 
   update the second smallest.
c) The logic will fail when the array size is 2. So find the smallest element by 
   comparison and store the results accordingly.

<强>代码

public static void main(String[] args) {

int[] values={13,23,3,45,56,0};
int smallest=values[0];
int beforeSmallest=smallest;

for(int num:values){

    if(num<smallest){
        beforeSmallest=smallest;
        smallest=num;
    }

    if((num<beforeSmallest)&&(num!=smallest)){
        beforeSmallest=num;
    }
}

if(values.length==2){
    if(values[0]<values[1]){
        smallest=values[0];
        beforeSmallest=values[1];
    }else{
        smallest=values[1];
        beforeSmallest=values[0];
    }

}

System.out.println(smallest+"--> Smallest");
System.out.println(beforeSmallest+"--> Before Smallest");

}
相关问题