Two Sum
1. Two Sum
μ μ λ°°μ΄ nums
κ³Ό μ μ target
μ΄ μ£Όμ΄μ§λ©΄
λ°°μ΄ λ΄μμ ν©μ΄ target
μ΄ λλ λ μ«μμ μΈλ±μ€λ₯Ό λ°ννλλ‘ μμ±νλΌ.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Only one valid answer exists.
Solution
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0..<nums.count {
for j in 1+i..<nums.count {
if nums[i] + nums[j] == target {
return [i, j]
}
}
}
return []
}
}
μ΄μ€ for
λ¬ΈμΌλ‘ λ κ°μ μμμ ν©μ΄ target
μ΄ λλμ§λ₯Ό νμΈνλ λ°©λ²μΌλ‘ ꡬννμλ€.
target
κ³Ό μΌμΉνλ ν©μ μ°Ύλλ€λ©΄ ν΄λΉ μμμ μΈλ±μ€λ₯Ό λ£μ λ°°μ΄μ λ°ννλ€.
π Reference
LeetCode-1-TwoSum