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

Single Number I & II

时间:2014-07-30 12:19:53      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   strong   io   for   问题   ar   amp   res   

Single Number I

问题描述:

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

解题思路:

既然除了某个元素出现一次外,其他所有元素都出现两次,那么可以异或数组的所有元素,得到的结果就是我们所要找的那个元素的值。

class Solution {
public:
    int singleNumber(int A[], int n) {
        if (0 == n)
            return 0;
        int result = A[0], i;
        for (i = 1; i < n; i++)
            result ^= A[i];
        return result;
    }
};


Single Number II

问题描述:

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

解题思路:

如果某个元素出现1次,而其他元素都出现3次,那么对所有元素的每个位进行求和,然后对3取余,得到的就是我们要找的元素相应位的值。

class Solution {
public:
    int singleNumber(int A[], int n) {
        int count[32] = {0};
        int result = 0;
        for (int i = 0; i < 32; i++) {
            for (int j = 0; j < n; j++) {
                if ((A[j] >> i) & 1) {
                    count[i]++;
                }
            }
            result |= ((count[i] % 3) << i);
        }
        return result;
    }
};



Single Number I & II,布布扣,bubuko.com

Single Number I & II

标签:style   strong   io   for   问题   ar   amp   res   

原文地址:http://blog.csdn.net/wan_hust/article/details/38295121

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