LeetCode 136. Single Number 的C语言实现,如何写一个长尾词来提问?
- 内容介绍
- 文章标签
- 相关推荐
本文共计250个文字,预计阅读时间需要1分钟。
给定一个非空整数数组,其中每个元素都恰好出现两次,除了一个元素。找出这个只出现一次的元素。注意:你的算法应该具有线性时间复杂度。你能否在不使用额外内存的情况下实现它?
示例 1:输入:[2, 2, 1]输出:1
Given anon-emptyarray of integers, every element appearstwiceexcept 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 ^ n = n
n ^ n = 0
因为题目说明只有一个数出现一次,其余都出现两次,出现两次的数异或以后为0,0与出现一次的数n异或为n
class Solution { public: int singleNumber(vector<int>& nums) { int s = 0; for(int c : nums) s ^= c; return s; } };
本文共计250个文字,预计阅读时间需要1分钟。
给定一个非空整数数组,其中每个元素都恰好出现两次,除了一个元素。找出这个只出现一次的元素。注意:你的算法应该具有线性时间复杂度。你能否在不使用额外内存的情况下实现它?
示例 1:输入:[2, 2, 1]输出:1
Given anon-emptyarray of integers, every element appearstwiceexcept 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 ^ n = n
n ^ n = 0
因为题目说明只有一个数出现一次,其余都出现两次,出现两次的数异或以后为0,0与出现一次的数n异或为n
class Solution { public: int singleNumber(vector<int>& nums) { int s = 0; for(int c : nums) s ^= c; return s; } };

