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

LeetCode 136、137:Single Number I & II

时间:2015-05-12 23:10:19      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:leetcode   位运算   single number   single numberii   

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?


Single Number II


Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

分析:


一个整形数组,除某个元素外,每个元素都出现了2次(Single NumberII中出现了3次),找出这个只出现一次的元素。要求,线性时间复杂度、不使用额外的空间。



Single Number 比较简单,由于其余元素都出现了两次,通过位运算中 N xor N = 0即可方便的找到这个只出现一次的元素。代码如下:


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



Single Number II要复杂的多,很难直观的找到算法。考虑每个元素的为一个32位的二进制数,这样每一位上出现要么为1 ,要么为0。对数组,统计每一位上1 出现的次数count,必定是3N或者3N+1 次。让count对3取模,能够获得到那个只出现1次的元素该位是0还是1。

代码如下:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int length = nums.size();
        int result = 0;
        for(int i = 0; i<32; i++){
            int count = 0; 
            int mask = 1<< i;
            for(int j=0; j<length; j++){
                if(nums[j] & mask)
                    count++;
            }
          <span style="color:#FF6666;">  if(count %3)</span>
                result |= mask;
        }
        return result;
    }
};

该方法同样适用于Single NumberI的解答。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int length = nums.size();
        int result = 0;
        for(int i = 0; i<32; i++){
            int count = 0;
            int mask = 1<< i;
            for(int j=0; j<length; j++){
                if(nums[j] & mask)
                    count++;
            }
           <span style="color:#FF6666;"> if(count %2)</span>
                result |= mask;
        }
        return result;
    }
};

对于Single Number II,网上还有一种与、异或等位操作的解法,尚未完全理解,先记录下


int singleNumber(int A[], int n)
{
	int one = 0, two = 0;
	for (int i = 0; i < n; i++)
	{
		two |= A[i] & one;
		one ^= A[i];
		int three = one & two;
		one &= ~three;
		two &= ~three;
	}
	return one;
}


LeetCode 136、137:Single Number I & II

标签:leetcode   位运算   single number   single numberii   

原文地址:http://blog.csdn.net/sunao2002002/article/details/45674029

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