136. Single Number

来源:互联网 发布:php soapheader 编辑:程序博客网 时间:2024/06/07 20:53

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?


采用异或运算可以不需要额外的内存,并且可以过一遍线性时间内运算完:

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

也可以估算其他方案:

1、最基本的暴力遍历。开辟一个变量记录当前值,与之后的对比,最坏情况O(n2)

2、开辟一个数组,遍历到一个就把对应位置加一,该方法问题空间分配大小不确定,假设确定的话,那么线性时间O(n)可以解决

原创粉丝点击