LeetCode_Single Number&Single NumberII

来源:互联网 发布:淘宝网 文胸故事模特 编辑:程序博客网 时间:2024/04/29 17:02

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?

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


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?

//对于这种类似的一系列问题,考虑使用位运算操作,将每一个数在计算机中都是有二进制位构成的,考虑每一位//不要考虑具体的数//思路:对于异或操作,满足交换律class Solution {public:    int singleNumber(int A[], int n) {        int ones=0;//记录对应位出现一次的位数,若对应位出现一次,则在ones中相应位置1        int twos=0;//记录对应位出现两次的位数,若对应位已经出现了2次,则在twos中相应位置1        for (int i=0;i<n;i++)        {            twos |= (ones&A[i]);//根据出现一次的位数以及当前数更新出现两次的位数            ones=ones^A[i];//根据当前数更新出现1次的位数,在ones中记载出现次数为1的话,若在A[i]中出现则清零,否则不变            int threes=~(twos&ones);//求出已经出现三次的位,并使得满足条件的位为0            //相应位出现三次后清零操作            ones=ones&threes;            twos=twos&threes;        }        return ones;    }};


0 0
原创粉丝点击