반응형

1. Two Sum (easy)

 

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

 

Example:

Given nums = [2, 7, 11, 15],

target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

 

 

Java Solution

import java.util.*;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                return new int[] {map.get(nums[i]), i};
            }
            map.put(target - nums[i], i);
        }
        return new int[]{};
    }
}

 

Kotlin Solution

class Solution {
    fun twoSum(nums: IntArray, target: Int): IntArray {
        val visited: MutableMap<Int, Int> = mutableMapOf()

        nums.forEachIndexed { i, num ->
            if (visited.containsKey(num)) {
                return@twoSum intArrayOf(visited[num]!!, i)
            }
            visited[target - num] = i
        }

        return intArrayOf()
    }
}

 

 

이 외에도 다양한 문제들의 해답 코드를 깃헙 저장소에서 확인할 수 있습니다. (Java, Kotlin)


 

반응형
반응형