LeetCode Single Number

本文探讨了在数组中寻找仅出现一次的元素的问题,并详细介绍了两种高效的解决方案:使用哈希表和位操作(异或)。同时提供了Java代码实现,便于理解和实践。

原题链接在这里:https://leetcode.com/problems/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?

题解:

首先会想到HashMap,HashSet的想法,但会用到extra O(n) space.

所以就要用到bit manipulation,这里和Single Number II非常相似, 32位的int, 每一位的count若是出现奇数,那么这一位就是用来组成single number的.

但这里有个更快的方法,就是用异或 ^ operator. 异或 every number in the array and the result would be the single number.

Method 1 Time Complexity: O(n). Space: O(n).

Method 2 Time Complexity: O(n). Space: O(1).

Method 3 Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int singleNumber(int[] nums) {
 3         /*Method 1
 4         if(nums == null || nums.length == 0)
 5             return Integer.MIN_VALUE;
 6         
 7         HashSet hs = new HashSet();
 8         for(int i = 0; i < nums.length; i++){
 9             if(!hs.contains(nums[i])){
10                 hs.add(nums[i]);
11             }else{
12                 hs.remove(nums[i]);
13             }
14         }
15         
16         Iterator it = hs.iterator();
17         int res = Integer.MIN_VALUE;
18         while(it.hasNext()){
19             res = (int)it.next();
20         }
21         
22         return res;
23         */
24         
25         /*Method 2
26         if(nums == null || nums.length == 0)
27             return Integer.MIN_VALUE;
28             
29         int [] bitCounter = new int[32];
30         for(int i = 0; i<32; i++){
31             for(int j = 0; j<nums.length; j++){
32                 bitCounter[i] += (nums[j]>>i&1); //error
33             }
34         }
35         int res = 0;
36         for(int i = 0; i<32; i++){
37             res += (bitCounter[i]%2)<<i;
38         }
39         return res;
40         */
41         
42         //Method 3
43         if(nums == null || nums.length == 0)
44             return Integer.MIN_VALUE;
45         int res = 0;
46         for(int j = 0; j < nums.length; j++){
47             res = res ^ nums[j];
48         }
49         return res;
50     }
51 }

跟上Single Number IISingle Number III.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825048.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值