码迷,mamicode.com
首页 > 其他好文 > 详细

letecode [136] - Single Number

时间:2019-06-10 18:25:54      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:结果   cep   solution   out   NPU   code   相同   algo   exit   

 

Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1
Example 2:

Input: [4,1,2,1,2]
Output: 4

 

题目大意

   给定一个非空数组,数组中只有一个元素只出现了一次,其他元素都出现了两次,求出现一次的元素。

理  解:

   异或数组所有元素结果即为所求元素。两数相同异或为0。任何数与0异或为它本身。比较简单的一题。

代 码 C++:

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

运行结果:

   执行用时 : 16 ms  内存消耗 : 9.7 MB

letecode [136] - Single Number

标签:结果   cep   solution   out   NPU   code   相同   algo   exit   

原文地址:https://www.cnblogs.com/lpomeloz/p/10999337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!