1

Write a method that when passed an array of integers arr, and an integer target, returns the last index at which target occurs in the array. Return -1 if the array is null or if target doesn’t exist in the array.

So I am using linear search to do this.

public static void linearSeach(int [] arr, target){
if( arr == null){
   return -1;
}
count = 0;
for (int i = 0; i< arr.length; i++){
    if( target == arr[i]){
       count ++;
}
}
// I cannot return both count and -1 so here is what I thought I should do
if( count >= 0){
return count;
}
else {
  return -1;
}}

Is this correct or the right approach?

1
  • 1
    No,it is asking for the last index Commented May 1, 2017 at 5:34

2 Answers 2

1

No, you are returning the number of times the target number appears in the array. You should return the index of the last time it appears :

if (arr != null) {
    for (int i = arr.length - 1; i >= 0; i--){
        if (target == arr[i]) {
            return i;
        }
    }
}
return -1;
Sign up to request clarification or add additional context in comments.

Comments

0
public static void linearSeach(int [] arr, target){
    if( arr != null) {      
        int i = arr.length - 1
        while (i>=0){
            if( target == arr[i]){
                 return i;
            } 
            i= i-1              
        }
    }
    return -1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.