首页 > 其他 > 详细

Leetcode Single Number

时间:2014-11-25 14:20:54      阅读:249      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/criseRabbit/p/4120747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!