singlenumber

ava基础知识:SingleNumber数组中找出只出现一次的数字

  题目是这样说的:

  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?

  对复杂度的要求是线性的,O(n)就可以了

  于是我一开始这样写也accept了就是利用一个hashmap,记录每个数字出现的个数。

  public class Solution {

  public int singleNumber(int[] A) {

  Map map=new HashMap();

  for(int i=0;i m:map.entrySet()){

  if(m.getValue()==1){

  return m.getKey();

  }

  }

  return 0;

  }

  }

  这个题的标准做法是利用异或运算的这两个法则:

  1. a ^ b = b ^ a

  2. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;

  举个例子:

  1^2^3^4^4^3^2的结果是啥呢?

  一眼大概开不出来

  根据上面两个法则,改变一下顺序吧

  改成2^2^3^3^4^4^1

  现在,结果一目了然了吧~

  显然是1呗。

  有了上面的例子,这道题就简单多了

  public class Solution {

  public int singleNumber(int[] A) {

  int result = A[0];

  for(int i = 1; i < A.length; i++){

  result = result ^ A[i];

  }

  return result;

  }

  }

  完事了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值