一、
1 public int findLast (int[] x, int y) 2 { 3 //Effects: If x==null throw NullPointerException 4 // else return the index of the last element 5 // in x that equals y. 6 // If no such element exists, return -1 7 for (int i=x.length-1; i > 0; i--) 8 { 9 if (x[i] == y) 10 { 11 return i; 12 } 13 } 14 return -1; 15 } 16 // test: x=[2, 3, 5]; y = 2 17 // Expected = 0
1、检测不到x[0],7行大于号应该改为等于。
2、x = NULL
3、x = [1, 2, 3], y = 3
4、x = [1, 2, 3], y = 1
二、
1 public static int lastZero (int[] x) 2 { 3 //Effects: if x==null throw NullPointerException 4 // else return the index of the LAST 0 in x. 5 // Return -1 if 0 does not occur in x 6 for (int i = 0; i < x.length; i++) 7 { 8 if (x[i] == 0) 9 { 10 return i; 11 } 12 } 13 return -1; 14 } 15 // test: x=[0, 1, 0] 16 // Expected = 2
1、只能返回第一个0的位置,未必是最后一个。
2、x = NULL
3、x = [1, 0]
4、x = [0, 1]