设为首页 加入收藏

TOP

leetcode 136 Single Number bBt Option
2019-07-13 20:10:48 】 浏览:57
Tags:leetcode 136 Single Number bBt Option

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 };

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇P1018 乘积最大(DP) 下一篇C语言实现-航空订票系统(飞机订..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目