SingleNumber [source code]


public class SingleNumber {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums) {
            Integer result = map.get(i);
            if (result == null) map.put(i, 1);
            else map.put(i, -1);
        }
        for (Map.Entry e : map.entrySet())
            if ((int) e.getValue() == 1) return (int) e.getKey();
        return 999;
    }

    public static void main (String[] args) {
        SingleNumber tester = new SingleNumber();
        int[] input1 = {2,2,1,3,3};
        assert tester.singleNumber(input1) == 2 : "fail 1";
        int[] input2 = {1,2,3,5,1,3,2,6,6};
        System.out.println(tester.singleNumber(input2));
    }
}

这个算法还是比较简单直接的, 就是最后的速度不怎么样, 21ms, 10%. 看看答案有没有什么更好的方法;


Problem Description

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?

Hide Tags Hash Table Bit Manipulation
Hide Similar Problems (M) Single Number II (M) Single Number III (E) Missing Number (M) Find the
Duplicate Number (E) Find the Difference

results matching ""

    No results matching ""