LeetCode Single Number

作者: 六尺帐篷 | 来源:发表于2016-12-17 13:33 被阅读33次

    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?

    题目

    给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。

    样例
    给出** [1,2,2,1,3,4,3]**,返回 4

    分析

    显然用异或就行了,因为其他的数均出现两次

    代码

    public class Solution {
        /**
          *@param A : an integer array
          *return : a integer 
          */
        public class Solution {
        public int singleNumber(int[] nums) {
        int ans =0;
        
        int len = nums.length;
        for(int i=0;i!=len;i++)
            ans ^= nums[i];
        
        return ans;
        
    }
    }
    }
    
    Paste_Image.png

    相关文章

      网友评论

      • Joahcy:大神 么看懂 能解释一下吗 谢谢

      本文标题:LeetCode Single Number

      本文链接:https://www.haomeiwen.com/subject/jniomttx.html