Intersection of Two Arrays II
350. Intersection of Two Arrays II
μ£Όμ΄μ§ λ κ°μ μ μ λ°°μ΄ nums1
κ³Ό nums2
μ
κ΅μ§ν© λ°°μ΄μ λ°ννλλ‘ μμ±νλΌ.
κ²°κ³Όμ κ° μμλ λ λ°°μ΄μ νμλλ νμλ§νΌ λͺ¨λ λνλμΌνλ€.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
Solution
class Solution {
func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var res: [Int] = []
var nums2 = nums2
for num in nums1 {
if nums2.contains(num) {
res.append(num)
nums2.remove(at: nums2.firstIndex(of: num)!)
}
}
return res
}
}
nums1
μ μμλ₯Ό num
λ‘ μννλ©΄μ nums2
μ ν¬ν¨νκ³ μλμ§ νμΈνλ€.
ν¬ν¨νκ³ μλ€λ©΄ num
μ κ²°κ³Όλ‘ λ°νν λ°°μ΄ res
μ λ£μ΄μ€λ€.
nums2
μ num
μ΄ λ€μ΄μλμ§ νμΈμ μλ£νμΌλ―λ‘,
νμΈν nums2
λ΄μ num
μμλ₯Ό μμ ν΄μ£Όμ΄μΌ νλ€.
π Reference
LeetCode-350-IntersectionOfTwoArrays2