BudiBadu Logo

Find Index

Array Easy 3 views
Like22

The objective is to locate the exact positional index representing the initial appearance of the target value within the nums array. This involves identifying the specific zero-indexed location where the element's value matches the requirement.

If the target exists within the dataset, the output must pinpoint its first occurrence; otherwise, it must return a negative indicator to signify the element's absence. This ensures a deterministic result for indexing operations within varying array structures.

Example 1:

Input: nums = [10, 20, 30], target = 20
Output: 1

Example 2:

Input: nums = [10, 20, 30], target = 40
Output: -1

Example 3:

Input: nums = [5, 5, 5], target = 5
Output: 0

Algorithm Flow

Recommendation Algorithm Flow for Find Index - Budibadu
Recommendation Algorithm Flow for Find Index - Budibadu

Best Answers

java
class Solution {
    public int find_index(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) return i;
        }
        return -1;
    }
}