zoukankan      html  css  js  c++  java
  • LeeCode-Single Number III

    Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

    For example:

    Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

    Note:

    1. The order of the result is not important. So in the above example, [5, 3] is also correct.
    2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

    题目很简单,但是通过这个题目让我见识了LeetCode众多大牛的存在。

    代码中,第一次了使用accumulate函数,然后还要bit_xor<int>()之类的C++11的function object。

    此处如果diff = INT_MIN, 那么 -diff 恰好会溢出到 INT_MIN. 之前并没有注意过这个问题。

     1 class Solution {
     2 public:
     3     vector<int> singleNumber(vector<int>& nums) {
     4         int diff = accumulate(begin(nums), end(nums), 0, bit_xor<int>());
     5         diff &= -diff;
     6         vector<int> result = {0, 0};
     7         for (auto num: nums) {
     8             result[!(diff & num)] ^= num;
     9         }
    10         return result;
    11     }
    12 };
  • 相关阅读:
    Java文档注释
    Java程序基本框架
    Java文件手动编译执行步骤
    JDK安装中配置Path无效解决办法
    JDK安装配置
    Java简单介绍运行机制
    python代码注释
    python从hello world开始
    python,pycharm,anaconda之间的区别与联系
    python环境配置
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/4752961.html
Copyright © 2011-2022 走看看