题目链接:https://leetcode.com/problems/single-number-ii/
题目:
Given an array of integers, every element appears three times 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、用HashMap,空间复杂度O(n)
2、用一个32位数组记录所有元素在每一位上1出现的次数,然后取模3,如果一个元素出现三次则该元素三次相加之和的每一位取模3结果都为0。
最后把该32位数组(此时表达的是二进制数)转为十进制就是要找的数。这种方法有通用性,即除了一个元素出现一次其余每个元素出现k次,我们都能找到该出现一次的元素。只要取模k就好了。
我经常把2^1当成2的1次方。。。java中没有 幂(mi)操作符。。
算法1:
public int singleNumber(int[] nums) { Map<Integer, Integer> maps = new HashMap<Integer, Integer>(); for (int i : nums) { if (maps.containsKey(i)) { int val = maps.get(i); if (val == 1) maps.put(i, val + 1); else maps.remove(i); } else { maps.put(i, 1); } } return (int) maps.keySet().toArray()[0]; }
算法2:
public int singleNumber(int[] nums) { int[] bitNums = new int[32]; int result = 0; for (int j = 0; j < 32; j++) { for (int i = 0; i < nums.length; i++) { bitNums[j] += nums[i] >> j & 1;// } result |= (bitNums[j] % 3) << j;// } return result; }