0

I want to find out if a key value is in array .. but it doesn't work..

class Solution {
  public int solution(int key, int[] array1) {
      int answer = 0;
      for(int i=0; i < array1.length; i++) {
          if(array1[i] == key) {
              answer = i;
          }
          else return -1;
      }
      return answer;
  }
}

ex ) key : 5 array1 : [1, 2, 3, 4, 5] answer : 4

2
  • 2
    It doesn't work because you immediately return -1 if the key isn't at the first position of the array without checking the other positions. Commented Dec 5, 2019 at 9:57
  • For things like this, your best bet by far is to use the debugger built into your IDE to step through the code statement by statement to see what's going wrong. Using the debugger is not an advanced skill, it's basically the next thing you should learn after "Hello, world". Happy coding! :-) Commented Dec 5, 2019 at 9:59

3 Answers 3

2

You should return an answer when you find a match, or when you finish the loop without finding a match.

You should not return -1 if the first element of the array doesn't match your key. You should check all the other elements of the array first.

  public int solution(int key, int[] array1) {
      for(int i=0; i < array1.length; i++) {
          if(array1[i] == key) {
              return i;
          }
      }
      return -1;
  }
Sign up to request clarification or add additional context in comments.

Comments

0

I think you need index of key as output and which you are getting correctly as index of array start from 0. Index for key as 5 is 4 which is correct.

Comments

0

You should put return outside for loop:

class Solution {
  public int solution(int key, int[] array1) {
      int answer = -1;
      for(int i=0; i < array1.length; i++) {
          if(array1[i] == key) {
              answer = i;
          }
      }
      return answer;
  }
}

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.