leetcode 136. 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?

题意概述

        就是说一堆数字序列,基本上每个数字都出现了两次,只有一个数字出现了一次。请找出这个数字。并且不分配额外内存。题目的tag是Hash table、Bit manipulate。这题并不难。。水的很,虽然题目提示了用hash和位操作来解。。但本着练习STL的目的,我还是另辟蹊径,使用了STL的accumulate算法来解题。

解题思路

        先把序列排序(NlogN),然后相等的元素就相邻了。这时因为正负数可以互相抵消。只要我们采取A-B+C-D+E-F……这种加法,最后没有被抵消掉的肯定就是那个落单的元素了。
        accumulate算法正是为了连续的累“加”操作准备的,只有我们自定义这个加法逻辑,该题很容易AC。

AC代码:

struct OP {
    int operator() (int x, int y)
    {
        i*=-1;
        return x+i*y;
    }
    OP():i(-1){};
    int i;
};
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return accumulate(nums.begin(), nums.end(), 0, OP());
    }
};

怎么样,简单吧。

posted on 2016-01-31 16:37  哼哼唧唧  阅读(91)  评论(0编辑  收藏  举报

导航