changki123's Foundation

LeetCode 1. Two Sum

2025. 5. 3. 15:56 | Go


728x90

문제

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

주어진 배열 nums에서 두 수를 골라 target이 되는 인덱스 쌍을 찾아라.

 


 

코드

func twoSum(nums []int, target int) []int {
    for i := 0; i < len(nums); i++ {
        for j := i + 1; j < len(nums); j++ {
            if nums[i]+nums[j] == target {
                return []int{i, j}
            }
        }
    }
    return nil
}

 

 

함수 시그니처

func twoSum(nums []int, target int) []int
  • nums []int → 정수 배열 입력
  • target int → 목표값
  • []int → 반환 타입 (정수 배열, 예: [0, 1])

 


 

return []int{i, j}

  • i, j는 target을 만드는 두 수의 인덱스
  • []int{i, j}로 묶어 배열로 반환
  • LeetCode 문제에서 반환 타입은 배열이므로 그냥 i, j만 반환하면 에러

예:

return []int{1, 2} // 1번, 2번 인덱스를 배열로 반환

 


 

return nil

  • 두 수를 찾지 못하면 nil 반환
  • Go에서 []int 타입은 nil로도 표현 가능 (즉, “없음” 상태)
  • LeetCode에서는 보통 정답이 반드시 있다고 가정하므로 이 줄은 잘 실행되지 않지만, 안전용으로 넣는 것이 좋음

 

 

GPT

func twoSum(nums []int, target int) []int {
    // 숫자값 → 인덱스를 저장할 맵 생성
    numMap := make(map[int]int)

    // nums 배열을 인덱스 i, 값 num으로 순회
    for i, num := range nums {
        // 현재 숫자와 합쳐서 target이 되는 숫자 계산
        complement := target - num

        // complement가 이미 map에 있는지 확인
        if j, ok := numMap[complement]; ok {
            // 찾았다면 인덱스 쌍 반환 (complement의 인덱스 j, 현재 인덱스 i)
            return []int{j, i}
        }

        // 현재 숫자 num과 인덱스 i를 map에 저장
        numMap[num] = i
    }

    // 문제 조건상 반드시 정답이 있다고 보장이 되지만,
    // 안전을 위해 값이 없으면 nil 반환
    return nil
}
728x90