📚

Find Index

Find Index - Explanation

쉬움 배열 O(n) O(1)

Problem Summary

Write a function that returns the index of a value in an array, or -1 if not found.

Go to Problem →

Detailed Explanation

이 문제는 **indexOf 메서드**를 사용하여 배열에서 요소의 위치를 찾는 방법을 학습합니다. **indexOf() 메서드** 배열에서 특정 요소의 첫 번째 인덱스를 반환합니다. 없으면 -1을 반환합니다. **사용 예시** - [1, 2, 3].indexOf(2) → 1 - [1, 2, 3].indexOf(5) → -1 **중복 요소가 있는 경우** 첫 번째로 발견된 인덱스만 반환합니다: - [1, 2, 2, 3].indexOf(2) → 1 **-1 반환의 의미** -1은 요소가 없음을 나타냅니다. 조건문에서 활용: ```javascript if (arr.indexOf(value) !== -1) { // 요소가 존재함 } ```

Solution Code

solution.js
function findIndex(arr, value) {
  return arr.indexOf(value);
}

Key Concepts from This Problem

1. indexOf 메서드
2. 인덱스 반환
3. -1 반환 의미
4. 선형 검색

Common Mistakes

-1이 반환되면 요소가 없다는 의미입니다
중복 요소가 있으면 첫 번째 인덱스만 반환됩니다
NaN은 indexOf로 찾을 수 없습니다

Hints

Hint 1: indexOf 메서드를 사용하세요.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(1)

Uses almost no additional memory

Related Tags

#배열 #indexOf #검색