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?

分析:找出一堆数组中只出现一次的那个,且时间复杂度为o(n);

思路1:

先排序,后依次比较两两是否相同,不同的那一组的第一个数就是。但需要使用一个复杂度为o(n)的排序法;

思路2:

直接统计每个数出现的次数,使用map,将数作为键,值为下标。若重复出现就将值置为-1,再次遍历即可;

思路3:

利用异或^的运算特性,相同的数异或为0,0和其他数异或为其他数,异或满足可交换,所以全体异或即可;

JAVA CODE

class Solution {
    public int singleNumber(int[] nums) {
        int m = 0;
        for(int i = 0; i < nums.length; i++){
            m = m ^ nums[i];
        }
        return m;
    }
}
原文地址:https://www.cnblogs.com/baichangfu/p/7468682.html