来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number-iii/
博主Github:https://github.com/GDUT-Rp/LeetCode
题目:给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。
示例 1:
输入:nums = [1,2,1,3,2,5] 输出:[3,5] 解释:[5, 3] 也是有效的答案。
示例 2:
输入:nums = [-1,0] 输出:[-1,0]
示例 3:
输入:nums = [0,1] 输出:[1,0]
提示:
2
2
2 <= nums.length <=
3
∗
1
0
4
3 * 10^4
3∗104
−
2
31
-2^{31}
−231 <= nums[i] <=
2
31
−
1
2^{31} - 1
231−1
除两个只出现一次的整数外,nums 中的其他数字都出现两次
map统计各个数的分布情况,然后判断是否符合条件。
C++class Solution {
public:
vector singleNumber(vector& nums) {
mapfreq;
for (int num: nums) {
freq[num]++;
}
vector ans;
for (const auto& [num, occ]: freq) {
if (occ == 1) {
ans.push_back(num);
}
}
return ans;
}
};
Golang
func singleNumber(nums []int) []int {
numCount := make(map[int]int)
for _, num := range nums {
numCount[num] += 1
}
var ans []int
for k,v := range numCount {
if v == 1 {
ans = append(ans, k)
}
}
return ans
}
Python
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
freq = Counter(nums)
return [num for num, occ in freq.items() if occ == 1]
复杂度分析
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
TODO



