136. Single Number 求数组中单一的数字

来源:互联网 发布:拼多多衣服比淘宝便宜 编辑:程序博客网 时间:2024/05/29 02:56

给定的整数的数组,除了其中一个元素出现一次,剩余每个元素出现两次。找出单独出现的这个元素。

你应该有一个线性时间复杂度的算法。你能实现它,而无需使用额外的内存?

we use bitwise XOR to solve this problem :first , we have to know the bitwise XOR in java1、0 ^ N = N2、N ^ N = 0So..... if N is the single numberN1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N= (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N= 0 ^ 0 ^ ..........^ 0 ^ N= N


public int singleNumber(int[] nums) {    int ans =0;        int len = nums.length;    for(int i=0;i!=len;i++)        ans ^= nums[i];        return ans;    }

用异或的解法,牛逼


其他解法

public class Solution {    public int singleNumber(int[] nums) {        int count=1;        int a=0;        Map<Integer,Integer> map=new HashMap();        for(int num:nums){            if(!map.containsKey(num)) map.put(num,count);            else map.put(num,count+1);        }                Set<Integer> ks = map.keySet();        Iterator<Integer> it = ks.iterator();        while (it.hasNext()) {            Integer key = it.next();            if(map.get(key)==1)    a=key;                               }        return a;    }}


阅读全文
0 0
原创粉丝点击