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

leetcode 136 Single Number bBt Option

时间:2019-07-13 20:02:16      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:turn   http   output   for   could   self   element   href   tco   

Linked Url:https://leetcode.com/problems/single-number/

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

solution:

The method is xor option, principles is  : 0 xor 0 = 0; 0 xor 1 = 1;any  num xor itself  =  0,so we pass the array and xor its elements all,so the result  which is we want.

Ac code follow: 

1 class Solution {
2 public:
3     int singleNumber(vector<int>& nums) {
4         int res = nums[0];
5         for(int i = 1;i < nums.size();++i)
6             res = nums[i]^res;
7         return res;
8     }
9 };

 

leetcode 136 Single Number bBt Option

标签:turn   http   output   for   could   self   element   href   tco   

原文地址:https://www.cnblogs.com/CS-WLJ/p/11181720.html

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