LeetCode 136. 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?

 

 


 题目标签:Hash Table

  题目给了我们一个 nums array, array 里只有一个数字是只出现一次的,剩余的都是出现2次的。让我们找出这个只出现一次的数字。

  方法一:

    首先想到的是Hash Set,遍历nums,遇到的数字没有在set 里的,就存入;遇到的数字已经在set 里了,就去除。剩下的数字就是那个只出现一次的数字。

  

  方法二:

    既然题目中还说了不需要用额外的空间,这里可以用XOR,它的特性就是 num ^ num = 0,把所有的数字都 XOR, 它会把相同的两个数字化为0,剩下的就是落单的那个数字。 

 

 

Java Solution 1:

Runtime beats 14.51% 

完成日期:05/16/2017

关键词:HashSet

关键点:利用HashSet来保存,去除数字,剩下的是落单的数

 1 class Solution 
 2 {
 3     public int singleNumber(int[] nums) 
 4     {
 5         HashSet<Integer> set = new HashSet<>();
 6         
 7         for(int num: nums)
 8         {
 9             if(set.contains(num))
10                 set.remove(num);
11             else
12                 set.add(num);
13         }
14         
15         return set.iterator().next();
16 
17     }
18 }

参考资料:N/A

 

Java Solution 2:

Runtime beats 41.35% 

完成日期:05/16/2017

关键词:Bit Manipulation

关键点:XOR

 1 class Solution 
 2 {
 3     public int singleNumber(int[] nums) 
 4     {
 5         int res = nums[0];
 6         
 7         for(int i=1; i<nums.length; i++)
 8             res ^= nums[i];
 9             
10         return res;
11     }
12 }

参考资料:N/A

 

LeetCode 题目列表 - LeetCode Questions List

posted @ 2017-10-25 11:03  Jimmy_Cheng  阅读(299)  评论(0编辑  收藏  举报