gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Give simple, common, and optimised Java solution public static int findFirst(intll…
- User
Give simple, common, and optimised Java solution
public static int findFirst(intll array, int num) ‹ // your code goes here
- Assistant
To implement the
findFirstmethod in Java, which will return the index of the first occurrence ofnumin the given integer arrayarray, you can use a simple loop to iterate through the array. Here's an optimized and common implementation:javapublic static int findFirst(int[] array, int num) { // Iterate through the array for (int i = 0; i < array.length; i++) { // Check if the current element is equal to num if (array[i] == num) { // Return the index of the first occurrence return i; } } // Return -1 if num is not found in the array return -1; }Explanation:
- The method iterates over each element in the array using a basic loop.