Skip to content

[Algorithm] 서울에서 김서방 찾기 #8

Description

@hwangJi-dev

📌 TODO

  • 문제 풀이
  • 정리

서울에서 김서방 찾기

💬 Idea

  • String형 배열 seoul의 element중 “Kim”의 위치 x를 찾기 위해 배열에 enumerated()를 사용하자
    • for문을 돌며 배열의 index도 함께 구하여 Kim이 위치하는 index를 알아내자

💬 풀이

func solution(_ seoul:[String])->String{varkimLocation:Int=0for(index, i)in seoul.enumerated(){if i =="Kim"{
kimLocation = index
break}}return"김서방은 \(kimLocation)에 있다"}

소요시간 : 4분 40초


💬 더 나은 방법?

  • 배열을 돌지 않고도 배열의 firstIndex 메서드를 활용하여 Kim의 위치를 찾을 수 있다.

    • "Kim"은 오직 한 번만 나타나기 때문에 최초로 위치하는 값이 유일하므로 firstIndex 메서드를 활용하면 더 쉽고 간단하게 구현이 가능한 문제였다.
    func solution2(_ seoul:[String])->String{return"김서방은 \(seoul.firstIndex(of:"Kim")!)에 있다"}

💬 문법 정리

✅ firstIndex(of:)

  • 컬렉션에서 지정된 값이 나타나는 첫 번째 인덱스를 반환한다 !!!

    varstudents=["Ben","Ivy","Jordell","Maxime"]iflet i = students.firstIndex(of:"Maxime"){students[i]="Max"}print(students)
    // Prints "["Ben", "Ivy", "Jordell", "Max"]"

✅ enumerated()

  • 쌍(n, x)의 시퀀스를 반환한다.

  • 여기서 n은 0에서 시작하는 연속적인 정수**(index)를 나타내고 x는 시퀀스의 요소(element)**를 나타냅니다.

    for(n, c)in"Swift".enumerated(){print("\(n): '\(c)'")}
    // Prints "0: 'S'"
    // Prints "1: 'w'"
    // Prints "2: 'i'"
    // Prints "3: 'f'"
    // Prints "4: 't'"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions