136Single Number

来源:互联网 发布:淘宝头条可以赚钱吗 编辑:程序博客网 时间:2024/05/16 02:06

题目链接: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?

解题思路:
这道题的常规解法是
1. 将数组元素作为 key,元素出现的次数作为 value,存入到 HashMap 中
2. 然后遍历一遍 HashMap,找到元素出现次数为 1 的元素。

但是题目希望我们不使用额外的空间来解题。

一种方法是:
1. 将每一个数组元素通过移位的方式,以二进制的形式存储到一个临时数组中
2. 临时数组中的每一位对应原数组元素二进制的每一位,临时数组的第 0 位为存储元素二进制的最低位
3. 将所有元素都累加到这个临时数组中
4. 若某个元素出现 2 次,那么临时数组中每一位出现 1 的次数都是 2 的倍数,如果我们统计完对每一位进行取余 2,那么结果中就只剩下那个出现一次的元素
5. 临时数组固定大小为32,因为整数最大为 32 位

第二种方法:
1. 依次对每一个元素进行异或操作
2. 由于相同的元素之间进行异或结果为 0,所以出现两次的元素都被消除了,最后只剩下只出现一次的元素
这种方法具有技巧性,不是很通用。

以上两种算法都参考了大神的思想,必须附上链接:http://blog.csdn.net/linhuanmars/article/details/22645599

小小的题总能玩出大花样,不可小觑!

代码实现:
常规解法:

public class Solution {    public int singleNumber(int[] nums) {        if(nums == null || nums.length == 0)            return 0;        HashMap<Integer, Integer> map = new HashMap();        for(int i = 0; i < nums.length; i ++) {            if(map.containsKey(nums[i]))                map.put(nums[i], 2);            else                 map.put(nums[i], 1);        }        int res = 0;        for(Map.Entry<Integer, Integer> t : map.entrySet()) {            if(t.getValue() == 1) {                res = t.getKey();                break;            }        }        return res;    }}
15 / 15 test cases passed.Status: AcceptedRuntime: 24 ms

改良后的第一种方法:最推荐

public class Solution {    public int singleNumber(int[] nums) {        if(nums == null || nums.length == 0)            return 0;        int[] digit = new int[32];        for(int i = 0; i < 32; i ++) {            for(int j = 0; j < nums.length; j ++) {                digit[i] += (nums[j] >> i) & 1;            }        }        int res = 0;        for(int i = 0; i < 32; i ++) {            digit[i] %= 2;            res += digit[i] << i;        }        return res;    }}
15 / 15 test cases passed.Status: AcceptedRuntime: 12 ms

改良后的第二种方法:技巧性强

public class Solution {    public int singleNumber(int[] nums) {        if(nums == null || nums.length == 0)            return 0;        int res = 0;        for(int i = 0; i < nums.length; i ++) {            res ^= nums[i];        }        return res;    }}
15 / 15 test cases passed.Status: AcceptedRuntime: 1 ms
0 0
原创粉丝点击