6/29每日一題(會傳兩個數組重複的部分,且元素必須是唯一)
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
n1_s, n2_s=set(nums1), set(nums2) #設定集合
return list(n1_s.intersection(n2_s))
#回傳兩個集合中重複的部份且元素是唯一
-----------------
def f():
set1=set(n1) #將數組1轉換成集合
result=set() #初始化集合
for n in n2:
if n in set1:
result.add(n) #如果是交集的元素就加入到集合
return list(result)
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁