没有规定说一定要从前往后循环数组。事实上,你也可以从数组的末尾开始,每轮循环向前推进一位。比如对于一个已经排好序的数组,你可以通过这种方式来寻找比给定数更小的最后一个数的索引位置,如以下的getIndexLastSmaller method所示。注意如果数组中所有数都比给定数大,method会返回-1,为什么能这么做?

public class ArrayWorker
{
   private int[ ] values;

   public ArrayWorker(int[] theValues)
   {
      values = theValues;
   }

   public int getIndexLastSmaller(int target)
   {
      for (int index = values.length - 1; index >= 0; index--)
      {
         if (values[index] < target)
             return index;
      }
      return -1;
   }

   public void printValues()
   {
     for (int val : values )
     {
       System.out.print(val + ", ");
     }
     System.out.println();
   }

   public static void main (String[] args)
   {
      int[] theArray = {-30, -5, 8, 23, 46};
      ArrayWorker worker = new ArrayWorker(theArray);
      System.out.println(worker.getIndexLastSmaller(50));
      System.out.println(worker.getIndexLastSmaller(30));
      System.out.println(worker.getIndexLastSmaller(10));
      System.out.println(worker.getIndexLastSmaller(0));
      System.out.println(worker.getIndexLastSmaller(-20));
      System.out.println(worker.getIndexLastSmaller(-30));
   }
}

在数组是class ArrayWorker的field的情况下,你需要在main method中创建一个ArrayWorker的object。此时你不需要给method传递额外的参数——它可以像其他object method一样直接访问object的field。



0:00

Given the following code segment what will be returned when you execute: getIndexLastSmaller(-13);

private int[ ] values = {-20, -15, 2, 8, 16, 33};

public int getIndexLastSmaller(int compare)
{
   for (int i = values.length - 1; i >=0; i--)
   {
      if (values[i] < compare) return i;
   }
   return -1; // to show none found
}
-15是从后往前第一个小于-13的元素,其索引值为1
3

Given the following code segment what will be returned when you execute: getIndexLastSmaller(7);

private int[ ] values = {-20, -15, 2, 8, 16, 33};

public int getIndexLastSmaller(int compare)
{
   for (int i = values.length; i >=0; i--)
   {
      if (values[i] < compare) return i;
   }
   return -1; // to show none found
}
注意数组中并没有索引为values.length的元素。
4


陈 欣

AADPS创始人

发表评论