zoukankan      html  css  js  c++  java
  • 【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>&)’

  • 相关阅读:
    安卓移动端css3动画卡顿解决方法
    PDO方法实现增删改查
    NPOI 操作笔记
    基于emoji 国际通用表情在web上的输入与显示的记录
    restful 规范
    set与map
    ES6解构赋值
    scss的基本用法
    学习vue的第一二三四五天
    React Hooks --- useState 和 useEffect
  • 原文地址:https://www.cnblogs.com/helloWaston/p/4482984.html
Copyright © 2011-2022 走看看