【LeetCode】136.Single Number

Given an 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?

 

Hide Tags
Hash Table Bit Manipulation
 题目要求是特定条件的,只有一个数字值出现一次
1 class Solution {
2 public:
3     int singleNumber(int A[], int n) {
4         int x;
5         for(size_t i=0; i<n; ++i)
6             x ^= A[i];
7         return x;
8     }
9 };
Status: Accepted
Runtime: 18 ms
Submitted: 3 months, 3 weeks ago
但是我觉得此处的x是未进行初始化的,查找C++Primer第五版,P40页有相应默认初始化定义:
“如果是内置类型的变量未被显示初始化,它的值由定义的位置决定。定义于任何函数体之外的变量被初始化为0。定义在函数体内部的内置类型变量将不被初始化。”
main函数也是函数,所以全局变量才会初始化为0,在类中的成员函数是否是初始化为0?这个还没有确定。
所以就修改了下
1 int singleNumber(int A[], int n) {
2     if (n < 1)
3         return NULL;
4     int x = A[0];
5     for(size_t i=1; i<n; ++i)
6         x ^= A[i];
7     return x;
8 }

此时竟然不AC了,提示Compile Error

Line 19: no matching function for call to ‘Solution::singleNumber(std::vector<int>&)’

posted @ 2015-05-06 19:43  HelloWaston  阅读(181)  评论(0编辑  收藏  举报