can anyone help me find what wrong with this code. I am trying to write a function method that determine the second to the last occurrence of a target in an integer array. Return -1 if not in the array.
任何人都可以帮我找到这个代码有什么问题。我试图编写一个函数方法,确定整数数组中目标的最后一次出现。如果不在数组中则返回-1。
public static int findSecondToLast(int [] a, int target) {
int [] b = new int[countOfTarget (a,target)];
int k =0;
for (int i = 0; i < a.length; i++){
if (a[i]==target){
b[k]=i;
k++;
return b[ countOfTarget (a,target) - 1];
}
}
return -1;
}
public static int countOfTarget (int[]a, int t){
int count = 0;
for (int i=0; i < a.length; i++) {
if (a[i] == t)
count++;
}
return count;
}
3 个解决方案
#1
3
Try changing your code as
尝试将代码更改为
public static int findSecondToLast(int[] a, int target)
{
int[] b = new int[countOfTarget(a, target)];
int k = 0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == target)
{
b[k] = i;
k++;
return b[ countOfTarget(a, target) - 1];
}
}
return -1;
}
return-1
statement must be outside for loop
return-1语句必须在for循环之外
#2
1
This problem is much easier if you simply scan in reverse order and return the second occurrence of the element:
如果您只是以相反的顺序扫描并返回第二次出现的元素,则此问题会更容易:
public static int findSecondToLast(int[] a, int terget) {
int firstFound = false;
for (int i = a.length - 1; i >= 0; --i) {
if (a[i] == target) {
if (firstFound) {
return i;
}
firsrFound = true;
}
}
return -1;
}
There's no need to use the countOfTarget
method and no need to iterate through the array three times (which is what your original code was doing).
不需要使用countOfTarget方法,也不需要遍历数组三次(这是您的原始代码所做的)。
#3
0
you need to change your function to this one:
你需要将你的功能改为这个:
public static int findSecondToLast(int [] a, int target)
{
int prev = -1;
int last = -1;
for (int i = 0; i < a.length; i++)
if (a[i] == target)
{
prev = last;
last = i;
}
return prev;
}
#1
3
Try changing your code as
尝试将代码更改为
public static int findSecondToLast(int[] a, int target)
{
int[] b = new int[countOfTarget(a, target)];
int k = 0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == target)
{
b[k] = i;
k++;
return b[ countOfTarget(a, target) - 1];
}
}
return -1;
}
return-1
statement must be outside for loop
return-1语句必须在for循环之外
#2
1
This problem is much easier if you simply scan in reverse order and return the second occurrence of the element:
如果您只是以相反的顺序扫描并返回第二次出现的元素,则此问题会更容易:
public static int findSecondToLast(int[] a, int terget) {
int firstFound = false;
for (int i = a.length - 1; i >= 0; --i) {
if (a[i] == target) {
if (firstFound) {
return i;
}
firsrFound = true;
}
}
return -1;
}
There's no need to use the countOfTarget
method and no need to iterate through the array three times (which is what your original code was doing).
不需要使用countOfTarget方法,也不需要遍历数组三次(这是您的原始代码所做的)。
#3
0
you need to change your function to this one:
你需要将你的功能改为这个:
public static int findSecondToLast(int [] a, int target)
{
int prev = -1;
int last = -1;
for (int i = 0; i < a.length; i++)
if (a[i] == target)
{
prev = last;
last = i;
}
return prev;
}