zoukankan      html  css  js  c++  java
  • [LeetCode] 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?

    给定一个数组,其中只有一个数字出现了1次,其他的数字都出现了2次。求出这个出现一次的数字。这道题利用XOR进行求解,如果两个数字相同,那么它们的XOR为0,然而0与任何数XOR都是任何数。所以用0与数组中各个数XOR,最后的结果就是那个只出现一次的数字。

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int res = 0;
            for (int num : nums)
                res ^= num;
            return res;
        }
    };
    // 13 ms
  • 相关阅读:
    事件处理(三)
    事件处理(二)
    事件处理(一)
    布局管理器(一)
    基本控件(三)
    基本控件(二)
    基本控件使用(一)
    Activity与界面
    多态
    final关键字
  • 原文地址:https://www.cnblogs.com/immjc/p/7146616.html
Copyright © 2011-2022 走看看