LeetCode Single Number

来源:互联网 发布:淘宝店铺为什么没访客 编辑:程序博客网 时间:2024/05/22 06:55

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?

题意:给出一个数组,其中只有一个元素只有一个,其它的都 有两个,找出只有一个的元素

思路:用异或,遍历数据,异或结果就是要找的元素。

代码如下:

class Solution {    public int singleNumber(int[] nums) {        int ans = nums[0];        for (int i = 1; i < nums.length; i++)        {            ans ^= nums[i];        }                return ans;    }}


0 0
原创粉丝点击