设为首页 加入收藏

TOP

[LeetCode] Single Number
2015-07-20 18:01:09 来源: 作者: 【 】 浏览:2
Tags: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?

href: https://oj.leetcode.com/problems/single-number/

解题思路:两个相同的数异或为0,然后分为正负两种情况考虑,就得到线性的解法。

class Solution {
public:
    int singleNumber(int A[], int n) {
        int zres=0;
        int fres=0;
        for(int i=0;i
  
   =0){
               zres ^=A[i]; 
            }else{
               fres ^=-A[i];
            }
            
        }
        if(0==zres&&0==fres){
            return 0;
        }else if(zres!=0){
            return zres;
        }else{
            return -fres;
        }
    }
};
  

public class Solution {
    public int singleNumber(int[] A) {
        int zres=0;
        int fres=0;
        for(int i=0;i
  
   =0){
               zres ^=A[i]; 
            }else{
               fres ^=-A[i];
            }
            
        }
        if(0==zres&&0==fres){
            return 0;
        }else if(zres!=0){
            return zres;
        }else{
            return -fres;
        }
    }
}
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ 3020 Antenna Placement ,二.. 下一篇Codeforces 155 C. Hometask

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: