首页 > 代码库 > Leetcode Single Number

Leetcode 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?

对于这道题,要求首先是线性的,其次最好不用到额外的空间,那么我们就用一个set来存储数字,同时用一个变量来记录。首先遍历set,若数组中这个数字已经出现了,则将变量num减去这个数字,若set中没有该数字,则将变量set+该数字,最终结果变量Num的值会等于那个出现一次的数字。

public class Solution {    public int singleNumber(int[] A) {  int single = 0;    Set<Integer> s = new TreeSet<Integer>();    for (int i : A) {      if (s.contains(i)) {        single = single - i;        s.remove(i);      } else {        s.add(i);        single = single + i;      }    }  return single;    }}

  

Leetcode Single Number