• single-number


    Given an array of integers, every element appears twice except for one. Find that single one.

    Note: 
    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

    import java.util.*;
    import java.util.Map.*;
    public class Solution {
        public int singleNumber(int[] A) {
          /*  HashMap<Integer,Integer> map=new HashMap<>();
            for(int i=0;i<A.length;i++){
                if(map.get(A[i])==null)
                    map.put(A[i],1);
                else map.put(A[i],map.get(A[i])+1);
            }
            
            for(Entry<Integer,Integer> entry:map.entrySet()){
                int a=entry.getValue();
                int k=entry.getKey();
                if(a==1)
                    return k;
            }
            
            return 0;
            */
            
            //使用异或,两个二进制数异或,相同就会为0,不同的为1。所以两个相同整数异或为0,而所有整数与0异或还是这个整数本身
            int result=A[0];
            for(int i=1;i<A.length;i++)
                result^=A[i];
            return result;
            
        }
    }
  • 相关阅读:
    深入理解java异常处理机制
    i2c总线
    运行时类型识别(RTTI)
    bcg界面库总结
    c++ 虚函数表
    宽字符,宽字符串
    c++异常处理
    内存管理
    c++中使用联合体
    MFC自定义消息
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8030014.html
Copyright © 2020-2023  润新知