标签:near except amp 有一个 note main 内容 ips app
https://leetcode.com/problems/single-number/
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
数组中其他数出现两次,仅有一个出现一次的。逐个字符进行异或来,当某个数字出现第二次时候数字就归为0。二进制计算逻辑如下:
二进制 异或 下一次的异或值 实际值
4 ==> 100 ==> 100 ^ 000 = 100 = 4
1 ==> 001 ==> 001 ^ 100 = 101 = 5
2 ==> 010 ==> 010 ^ 101 = 111 = 7
1 ==> 001 ==> 001 ^ 111 = 110 = 6
2 ==> 010 ==> 010 ^ 110 = 100 = 4
Cpp:
#include <stdio.h>
#include <vector>
using std::vector;
class Solution {
public:
int singleNumber(vector<int>& nums) {
int aNum = 0;
for (int i = 0; i < nums.size(); i++) {
aNum ^= nums[i];
}
return aNum;
}
};
int main()
{
// 使用内容
Solution nSolution;
vector<int> nums;
nums.push_back(2);
nums.push_back(1);
nums.push_back(2);
nSolution.singleNumber(nums);
return 0;
}
Python:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
r_nums = 0
for num in nums:
r_nums ^= num
return r_nums
Tips:按tags刷会比较有效率。
https://leetcode.com/problemset/all/?topicSlugs=string
https://leetcode.com/problems/unique-email-addresses
https://leetcode.com/problems/to-lower-case
https://leetcode.com/problems/jewels-and-stones
https://leetcode.com/problems/single-number
标签:near except amp 有一个 note main 内容 ips app
原文地址:https://www.cnblogs.com/17bdw/p/10358167.html