Single Number

来源:互联网 发布:牛耳软件教育 编辑:程序博客网 时间:2024/04/30 02:52

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?

int SingleNumber(int a[],int n){    int num=0;    for(int i=0;i<n;i++)        num^=a[i];    return num;}

题目要求要有O(n)的时间复杂度,这道题目考查的位运算的知识,任何一个数和本身异或为0,而同0异或得到的是其本身。因此通过0同数组所有元素异或就可以得到数组中单独的一个元素。

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?

这题重复的次数为三次,无法采用上次的方法。这里采用先将数组排序,再得出单独的元素。实现也非常简单。

int SingleNumber(int a[],int n){    if(N<=0)        return -1;    if(n==1)          //只有一个元素        return a[0];    sort(a,a+n);    int j=0;  //记录重复的次数    for(int i=0;i<n-1;i++)    {        if(a[i]==a[i+1])            j++;        else        {            if(j<3)  //这里将j<3改为j<2适应上题的情况            return a[i];            j=1;        }    }    return a[n-1];  //最后一种情况,单独元素在末尾}
0 0
原创粉丝点击