首页 > 其他 > 详细

leetcode 136. Single Number

时间:2016-01-31 17:18:44      阅读:152      评论:0      收藏:0      [点我收藏+]

题目原文

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

怎么样,简单吧。

leetcode 136. Single Number

原文:http://blog.csdn.net/guodongxiaren/article/details/50615067

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!