1. Two Sum
문제
숫자로 이루어진 배열과, 숫자로된 타겟을 입력받아서 배열에서 타켓을 만들 수 있는 숫자의 인덱스를 반환.
만약에 배열 [1, 3, 6, 7]과 타겟 8을 입력 받는다면 [0, 3]를 반환한다
답
|
|
설명
우선, nums에 있는 두 값으로 target을 만들어야 함으로
nums에 있는 A + B = target이라 생각하고 A = target - B로 생각해서
nums에 B가 있는지 확인하고, B가 있다면 그 index로 배열을 만들어서 리턴합니다.
Leetcode
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.
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
- 2 <= nums.length <= 104
- 109 <= nums[i] <= 109
- 109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?