8/9 每日一題(找出重複與缺失)
You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4] Output: [2,3]
Example 2:
Input: nums = [1,1] Output: [1,2]
Constraints:
2 <= nums.length <= 1041 <= nums[i] <= 104
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
res=[]
nums_set=set()
for i in nums:
if i in nums_set:
res.append(i) #找到重複
nums_set.add(i)
for i in range(1,len(nums)+1):
if i not in nums_set:
res.append(i) #找到缺失值
break
return res
----------------------------參考解答
import statistics
from statistics import mode
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
l=[]
s=set(range(1,len(nums)+1))
l.append(mode(nums))
l.append((list(s-set(nums)))[0])
return l#使用statistics中的mode找出眾數,在這裡也就是重複的值
#製作s=1-n集合
#l=初始化空list
#將重複的值加入l
#將s的集合減nums的集合 也就是集合的差集,也就是缺失的值,將該元素轉換成list再取出元素加入l
標籤: leetcode

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