[Leetcode] 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?

题意:给定一未排序的数组,其中只有一个数仅出现一次,其余都出现两次,找到仅出现一次的这个数。

思路:一般的暴力解法或者先排序,后遍历。显然这两种种做法不行,时间复杂度上没法满足线性。所以采用逻辑异或来解题。逻辑异或有几个特点:

一、异或满足交换律;二、相同两个数异或为0;三、0异或一个数为那个数本身。十位数的异或,先将其转变二进制,然后进行异或。参考了LeetCode OJ代码如下:

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) 
 4     {
 5         int res=0;
 6         for(int i=0;i<n;++i)
 7         {
 8             res^=A[i];
 9         }      
10         return res;    
11     }
12 };

同样的思路还有一种解法,牛客网@setsail,这种解法也是根据相同数异或为0的特性,找到仅出现一次的那个数。

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) 
 4     {
 5         if(n==1)
 6             return A[0];
 7         while(n>=2)
 8         {
 9             A[n-2]^=A[n-1];
10             n--;
11         }
12         return A[0];
13     }
14 };

 

转载于:https://www.cnblogs.com/love-yh/p/7198768.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值