4月活动第28天 面试题第56题:数组中数字出现的次数(中等)
-
题目:一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
-
解题思路:hashmap记录每个数字出现的次数,太笨了。。
class Solution {
public int[] singleNumbers(int[] nums) {
HashMap<Integer,Integer> hash = new HashMap<>();
List<Integer> ans = new ArrayList<Integer>();
hash.put(nums[0],1);
for(int i=1;i<nums.length;i++){
if(hash.containsKey(nums[i])){
hash.put(nums[i],hash.get(nums[i])+1);
}else{
hash.put(nums[i],1);
}
}
for(Map.Entry<Integer,Integer> entry:hash.entrySet()){
if(entry.getValue() == 1){
ans.add(entry.getKey());
}
}
Integer[] rest = new Integer[ans.size()];
ans.toArray(rest);
int[] ansL = new int[ans.size()];
for(int i=0;i<ans.size();i++) ansL[i] = rest[i];
return ansL;
}
}
- 题解做法:甜姨的做法~~
class Solution {
public int[] singleNumbers(int[] nums) {
int sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, zeroCount = 0;
for (int num : nums) {
if (num == 0) {
zeroCount += 1;
}
min = Math.min(min, num);
max = Math.max(max, num);
sum ^= num;
}
// 需要特判一下某个数是0的情况。
if (zeroCount == 1) {
return new int[]{sum, 0};
}
int lo = min, hi = max;
while (lo <= hi) {
// 根据 lo 的正负性来判断二分位置怎么写,防止越界。
int mid = lo < 0 ? lo + hi >> 1 : lo + (hi - lo) / 2;
int loSum = 0, hiSum = 0;
for (int num : nums) {
if (num <= mid) {
loSum ^= num;
} else {
hiSum ^= num;
}
}
if (loSum != 0 && hiSum != 0) {
// 两个都不为0,说明 p 和 q 分别落到2个数组里了。
return new int[]{loSum, hiSum};
}
if (loSum == 0) {
// 说明 p 和 q 都比 mid 大,所以比 mid 小的数的异或和变为0了。
lo = mid;
} else {
// 说明 p 和 q 都不超过 mid
hi = mid;
}
}
// 其实如果输入是符合要求的,程序不会执行到这里,为了防止compile error加一下
return null;
}
}
作者:sweetiee
链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solution/shi-yao-zhe-ti-huan-ke-yi-yong-er-fen-cha-zhao-bi-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。