题目一代码:
- public intfindLast(int[] x, inty) {
- //Effects: If x==null throw
- NullPointerException
- // else return the index of the last element
- // in x that equals y.
- // If no such element exists, return -1
- for (inti=x.length-1; i> 0; i--)
- {
- if (x[i] == y)
- {
- return i;
- }
- }
- return -1;
- }
- // test: x=[2, 3, 5]; y = 2
- // Expected = 0
1、第七行i>0,使得数组缺少第一个元素,应该改为i>=0
2、x = [];
3、x = [2,3,4] y=3;
4、x = [1,2,0] y=3;
题目二代码:
- public static intlastZero(int[] x) {
- //Effects: if x==null throw
- NullPointerException
- // else return the index of the LAST 0 in x.
- // Return -1 if 0 does not occur in x
- for (inti= 0; i< x.length; i++)
- {
- if (x[i] == 0)
- {
- return i;
- }
- } return -1;
- }
- // test: x=[0, 1, 0]
- // Expected = 2
1、第六行,查找最后一个应该从数组最后一位查找for(int i=x.length-1;i>=0;i--);
2、x = [];
3、x = [2,3,4];
4、x = [1,2,0];
时间: 2024-10-18 02:34:32