Two Sum

2025. 1. 5. 13:04·PS/LeetCode
반응형

문제

https://leetcode.com/problems/two-sum/submissions/1498086275/

입력

두개의 값을 더해서 target을 만들 수 있는가. 방법은 단 한개만 존재

- 2 <= nums.length <= 10^4
- 10^9 <= nums[i] <= 10^9
- 10^9 <= target <= 10^9

결과

ans: [Int] = 두개의 값의 인덱스를 배열에 담아 리턴

해석

현재 키와 (target - 현재 키)의 딕셔너리 존재 여부를 파악한다.

코드

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var hash: [Int: Int] = [:] // key: element, value: number

        var ans: [Int] = []

        for (index, num) in nums.enumerated() {
            let pair = target - num 
            if let pairIndex = hash[pair] {
                ans.append(pairIndex)
                ans.append(index)
                return ans 
            }
            hash[num] = index
        }
        return ans
    }
}

 

반응형

'PS > LeetCode' 카테고리의 다른 글

Product of Array Except Self  (0) 2025.01.05
Best Time to Buy and Sell Stock  (0) 2025.01.05
[LeetCode] 3. Longest Substring Without Repeating Characters  (0) 2024.10.24
[LeetCode] 647. Palindromic Substrings  (0) 2024.10.15
[LeetCode] 459. Repeated Substring Pattern  (0) 2024.10.15
'PS/LeetCode' 카테고리의 다른 글
  • Product of Array Except Self
  • Best Time to Buy and Sell Stock
  • [LeetCode] 3. Longest Substring Without Repeating Characters
  • [LeetCode] 647. Palindromic Substrings
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (304)
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (37)
        • swift (32)
        • python (4)
        • Kotlin (1)
      • iOS (132)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (32)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (13)
        • 어노테이션 (1)
        • 튜토리얼 (11)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
      • AI (0)
        • 이론 (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    프로그래머스
    property
    Spring
    AVFoundation
    dispatch
    SwiftUI
    protocol
    백준
    boostcamp
    dfs
    Tuist
    IOS
    dp
    UIKit
    투포인터
    lifecycle
    concurrency
    GIT
    Swift
    CS
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
Two Sum
상단으로

티스토리툴바