牛客 出现一次的数字

https://www.nowcoder.com/practice/0bc646909e474ac5b031ec6836a47768?tpId=46&&tqId=29044&rp=1&ru=/ta/classic-code&qru=/ta/classic-code/question-ranking

题目描述

现在有一个整数类型的数组,数组中素只有一个元素只出现一次,其余的元素都出现两次。

注意:

你需要给出一个线性时间复杂度的算法,你能在不使用额外内存空间的情况下解决这个问题么?

示例1
输入

[1,0,1]

返回值

0

一、 map<int,int>实现
代码
class Solution {
public:
    /**
     * 
     * @param A int整型一维数组 
     * @param n int A数组长度
     * @return int整型
     */
    int singleNumber(int* A, int n) {
        // write code here
		map<int, int>  mapp;
		for(int i=0;i<n;i++){
			mapp[A[i]]++;
		}
		map<int, int>::iterator iter;
    	for(iter = mapp.begin();iter != mapp.end();iter++){
			if(iter->second==1){
				return iter->first;
			}
    	}
    }
};
二、 异或实现

因为每个元素只出现一次或两次,且两个相同的数异或值为0,任何数和0异或值为它本身 因此对每个值进行异或最后值即为答案

class Solution {
public:
    /**
     * 
     * @param A int整型一维数组 
     * @param n int A数组长度
     * @return int整型
     */
    int singleNumber(int* A, int n) {
        // write code here
		int res = 0;
		for(int i=0;i<n;i++){
			res ^= A[i];
		}
		return res;
    }
};

个人觉得用map<int,int>比较好,当元素个数>2时,异或就无用武之地了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值