【leetcode】136. 只出现一次的数字
【leetcode】136. 只出现一次的数字
- 题目
- python3语言
- C++语言
题目
python3语言
代码1:
class Solution(object):
def singleNumber(self, nums):
""" :type nums: List[int] :rtype: int """
newList=list(set(nums))*2
for i in nums:
newList.remove(i)
return newList[0]
代码1,运行结果:
采用求和相减法:
代码2
class Solution(object):
def singleNumber(self, nums):
""" :type nums: List[int] :rtype: int """
return sum(set(nums))*2-sum(nums)
代码2,运行如下:
代码3:
思路,异或法:
2^2^1=2^1^2
具体代码如下:
class Solution:
def singleNumber(self, nums) :
res = 0
for i in nums:
res = res ^ i
return res
代码3,运行如下:
C++语言
代码1:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res=0;
for (int num:nums) { res^=num;}
return res;
}
};
代码1,运行如下:
还没有评论,来说两句吧...