Leetcode: Single Number

来源:互联网 发布:股票数据 excel 编辑:程序博客网 时间:2024/05/02 00:12

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?

思路1:使用HashMap来,key存值,value存该值出现的次数。在得到的HashMap中找Value为1的key。这样虽然实现linear runtime complexity,但是使用了额外的内存空间,当做练习HashMap。

Solution 1: (run time 452ms)

public class Solution {    public int singleNumber(int[] A) {        if (A == null || A.length == 0) {            return -1;        }                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();            for (int i = 0; i < A.length; i++){               if (!map.containsKey(A[i])) {                   map.put(A[i], 1);               } else {                   map.put(A[i], 2);               }            }                        for (int i = 0; i < A.length; i++) {                if (map.get(A[i]) == 1) {                    return A[i];                }            }                        return -1;        }}

思路2: 先sort数组,使数组从小到大排列,然后依次和左右相邻的元素比较。但是Arrays.sort(A)的时间复杂度不为O(n)。

Solution 2: (run time 436ms)

public class Solution {    public int singleNumber(int[] A) {        if (A == null || A.length == 0) {            return -1;        }                Arrays.sort(A);        if (A.length == 1 || A[0] != A[1]) {        return A[0];        }        for (int i = 1; i < A.length; i++) {            if (i == A.length - 1 || (A[i] != A[i - 1] && A[i] != A[i + 1])) {                return A[i];            }        }                return -1;    }}

思路3:使用异或思想。不同为1,相同为0。这样相同的俩个数都能相互抵消,剩下一个数以为答案。时间和空间复杂度都达到要求。


Solution 3: (run time 392ms)

public class Solution {    public int singleNumber(int[] A) {        if (A == null || A.length == 0) {    return -1;    }        int rst = 0;    for (int i = 0; i < A.length; i++) {    rst ^= A[i];    }    return rst;    }}



0 0