Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
2 tasks done
hwangJi-dev opened this issue Aug 1, 2022 · 0 comments
Closed
2 tasks done

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

hwangJi-dev opened this issue Aug 1, 2022 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Aug 1, 2022

📌 TODO

  • 문제 풀이
  • 정리

서울에서 김서방 찾기

💬 Idea

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

💬 풀이

func solution(_ seoul:[String]) -> String {
    var kimLocation: Int = 0
    
    for (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:)

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

    var students = ["Ben", "Ivy", "Jordell", "Maxime"]
    if let 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'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant