zoukankan      html  css  js  c++  java
  • 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;
            
        }
    }
  • 相关阅读:
    如何分配资源和管理资源
    让Project把周六和周日也计算工期
    Project设置子任务
    pytest-配置文件
    pytest-fixture
    pytest-标记
    pytest-断言
    pytest-参数化
    pytest入门
    maven-插件
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8030014.html
Copyright © 2011-2022 走看看