twoSum#
λ¬Έμ #
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.
constraints#
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
think#
\(O(n^2)\)μ μ΄μ€ for λ¬Έμ λλ©΄μ brute forceλ‘ μμ νμμ νλ©΄μ ν μ μκΈ΄ νλ€. νμ§λ§ λ¬Έμ μ μ νμμ nums 리μ€νΈμ ν¬κΈ°κ° λ§€μ° ν΄ μ μλ€λ μ κ³Ό νλμ μμμ ν¬κΈ°λ λ§€μ° ν΄ μ μλ€λ μ μ΄ μ‘΄μ¬νλ κ±Έλ‘ λ΄μλ μ’μ νμ΄λ‘λ 보μ΄μ§ μλλ€. O(n)μ μκ°λ³΅μ‘λλ‘ μ€μ΄λ λ°©λ²μ λν κ³ λ―Όμ΄ νμνλ€.
hash mapμ λν΄μ μκ°ν΄λ³Ό νμκ° μλ λ¬Έμ μ΄λ€.
python#
import sys, os
problem_num = "twoSum"
path = os.getcwd() + f"\\txt\\{problem_num}" + ".txt"
sys.stdin = open(path, "r")
input = sys.stdin.readline
nums = list(map(int, input().split()))
target = int(input())
from collections import deque
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
result = []
popidx = 0
nums = deque(nums)
while nums:
start = nums.popleft()
popidx += 1
for idx, i in enumerate(nums):
if start + i == target:
result = [popidx - 1, idx + popidx]
break
return result
answer = Solution().twoSum(nums, target)
answer
[0, 1]
javascript#
1/**
2 * @param {number[]} nums
3 * @param {number} target
4 * @return {number[]}
5 */
6
7var twoSum = function (nums, target) {
8 let popIndex = 0;
9 while (nums.length > 0) {
10 let start = nums.shift();
11 popIndex++;
12 for (let idx = 0; idx < nums.length; idx++) {
13 if (start + nums[idx] === target) {
14 result = [popIndex - 1, idx + popIndex];
15 break;
16 }
17 }
18 }
19 return result;
20};
Java#
class Solution {
public int[] twoSum(int[] nums, int target){
for (int i=0; i< nums.length;i++){
for (int j = i+1;j<nums.length;j++){
if (nums[j] == target-nums[i]){
return new int[] {i,j};
}
}
}
return null;
}
}