58.剑指Offer-数组中只出现一次的数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuicanxingchen123456/article/details/88981029

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

解题思路

两个不相等的元素在位级表示上必定会有一位存在不同,将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。

diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public void FindNumsAppearOnce(int[] nums, int num1[], int num2[]) {
    int diff = 0;
    for (int num : nums)
        diff ^= num;
    diff &= -diff;
    for (int num : nums) {
        if ((num & diff) == 0)
            num1[0] ^= num;
        else
            num2[0] ^= num;
    }
}

另一种空间复杂度高的hashmap的方式:

import java.util.HashMap;

public class FindNumsAppearOnce {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] array = { 1, 1, 2, 2, 3, 4, 5, 5 };
		FindNums(array);
	}

	public static void FindNums(int[] array) {
		HashMap<Integer,Integer> hash=new HashMap<Integer, Integer>();
		for(int i=0;i<array.length;i++){
			if(hash.containsKey(array[i])){
				hash.put(array[i], hash.get(array[i])+1);
			}else{
				hash.put(array[i], 1);
			}
		}
		for(Integer key:hash.keySet()){
			if(hash.get(key)==1){
				System.out.println(key);
			}
		}
	}
	
}
//输出结果
3
4

猜你喜欢

转载自blog.csdn.net/cuicanxingchen123456/article/details/88981029