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

LeetCode 136. Single Number

时间:2016-11-18 07:19:05      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:info   ice   except   mem   href   memory   question   ber   run   

136. Single Number

  • Total Accepted: 173470
  • Total Submissions: 331880
  • Difficulty: Easy
  • Contributors: Admin

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?

Subscribe to see which companies asked this question

题意:给你一个动态数组,里面的数只有一个数出现过一次其余的数都出现过两次,让你在不另辟空间的情况下用O(n)的复杂度实现,真是神奇的算法,能想到的也只有快排那些O(n*lgn)的东西
实现:因为A和A的异或等于0,而A和0的异或等于A,所以将整个数组遍历每个数异或一遍的结果就是要找的那个数,是不是很神奇
 
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int i = 1;
        while(i<nums.size())
        {
            nums[i]=nums[i-1]^nums[i];
            i++;
        }
        return nums[i-1];
    }
};
 

LeetCode 136. Single Number

标签:info   ice   except   mem   href   memory   question   ber   run   

原文地址:http://www.cnblogs.com/Xycdada/p/6076105.html

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