zoukankan      html  css  js  c++  java
  • [Leetcode] Single Number

    Single Number 题解

    题目来源:https://leetcode.com/problems/single-number/description/


    Description

    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?

    Solution

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int res = nums[0];
            int size = nums.size();
            for (int i = 1; i < size; i++) {
                res ^= nums[i];
            }
            return res;
        }
    };
    

    解题描述

    这道题题意是,给出一个数组,数组中有一个数字只会出现一次,其他所有数字都会出现两次。另外,解法上题目要求时间复杂度和空间复杂度均为常数级别。

    要使时间复杂度保持常数级别,第一个想到的可能是采用哈希。但是哈希会造成O(n)的空间复杂度,并且最终查找到只出现一次的那个数字的查找过程会造成额外的时间开销。

    上面给出的是采用异或的解法,利用相同的数字异或为0的性质,将数组中所有数字进行异或之后,最终的结果就是要查找的只出现一次的数字。

  • 相关阅读:
    alpha版本发布前的进度
    1.26~1.27
    1.23~1.25
    1月21日~1月22日工作情况
    1月17日工作情况
    1月16日小组开会
    1月15日工作进度
    1月12日~1月14日工作进度
    linux下的动态链接库管理
    小组第一次小组讨论
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8685849.html
Copyright © 2011-2022 走看看