只出现一次的数字题型总结

只出现一次的数字1

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1

示例 2:

输入: [4,1,2,1,2]
输出: 4

来源:力扣(LeetCode)
 

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int bit_num=0;
        for(auto c:nums)
        {
            bit_num^=c;
        }
        int tmp=bit_num&(-bit_num);
        int ret1=0;
    
        for(int a:nums)
        {
            if(a&tmp)
            {
                ret1^=a;
            }
        }
       
        return vector<int>{ret1,ret1^bit_num};
    }
};

只出现一次的数字2

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。

说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,3,2]
输出: 3

示例 2:

输入: [0,1,0,1,0,1,99]
输出: 99

来源:力扣(LeetCode)

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int once=0;
        int twce=0;
        for(auto c:nums)
        {
            once=(once^c)&(~twce);
            twce=(twce^c)&(~once);
        }
        return once;
    }
};

只出现一次的数字3

给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。

示例 :

输入: [1,2,1,3,2,5]
输出: [3,5]

注意:

    结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
    你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?

来源:力扣(LeetCode)
 

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int bit_num=0;
        for(auto c:nums)
        {
            bit_num^=c;
        }
        int tmp=bit_num&(-bit_num);
        int ret1=0;
    
        for(int a:nums)
        {
            if(a&tmp)
            {
                ret1^=a;
            }
        }
       
        return vector<int>{ret1,ret1^bit_num};
    }
};

扩展:给定一个非空整数数组,某个元素只出现了k次,其余每个元素均出现了n次。找出那个只出现了k次的元素

#include <stdio.h>
#include<stdlib.h>
#include <iostream>
#include<vector>
using namespace std;
void  test(vector<int> &arr, int k, int n)
{
	size_t count[32] = { 0 };
	for (int i = 0; i < 32; i++) 
	{
		for (auto num:arr)
		{
			count[i] += (num>> i) & 1;
		}
	}
	int ret = 0;
	for (int i = 0; i < 32; i++) 
	{
		count[i] %= n;
		count[i] /= k;
		ret += count[i] << i;
	}
 	printf("%d", ret);
}


int main()
{
	vector <int> arr = { 2, 2, 2, 2, 5 };
	test(arr,1, 4);
	system("pause");
	return 0;
}

 

 

 

 

  • 18
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 24
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值