出现一次的数字

题意: 在一个非空数组中,找出只出现了一次的数字 ( 其他的均出现了两次 )



第一种、 map
	class Solution {
	    public int singleNumber(int[] nums) {
	        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
	        
	    	for (int i = 0; i < nums.length; i++) {
	    		if(map.containsKey(nums[i])) {
	    			map.remove(nums[i]);
	    		}else {
	    			map.put(nums[i], nums[i]);
	    		}
			}
	    	
	    	int res = 0;
	    	for ( Integer k : map.keySet() ) {
				res = map.get(k);
			}
	    	
	    	return res;
	    }
	}

set

	class Solution {
	    public int singleNumber(int[] nums) {
	    	Set<Integer> set = new HashSet<Integer>();
	    	
	    	for (int i = 0; i < nums.length; i++) {
	    		if(set.contains(nums[i])) {
	    			set.remove(nums[i]);
	    		}else {
	    			set.add(nums[i]);
	    		}
			}
	    	
	    	return (int)set.toArray()[0];
	    }
	}


第二种、异或 ⭐

思路: 位运算
两个相同的数字异或,结果为0
和 0 异或的数字 == 它本身

	class Solution {
	    public int singleNumber(int[] nums) {
	    	int res = 0;
	    	for (int i = 0; i < nums.length; i++) {
				res = res ^ nums[i];
			}
	    	return res;
	    }
	}


第三种、数学

思路: 因为每个数字均出现两次,只有一个出现一次.

公式:   2*(a+b+c) - (a+a+b+b+c) = c
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值