• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

LeetCode——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?

给定一个整数数组,当中除一个外每一个元素都出现两次。找出那个。

说明:你的算法应该有线性的时间复杂性。你能够不用额外的内存来实现吗?

最直接的思路是使用哈希表来保存元素和出现的次数。

可是使用了新的空间。

	public int singleNumber(int[] A) {
		HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
		for(int i=0;i<A.length;i++){
			if(map.get(A[i]) != null)
				map.put(A[i], map.get(A[i])+ 1);
			else
				map.put(A[i], 1);
		}
		for(Map.Entry<Integer,Integer> m : map.entrySet())
			if(m.getValue() == 1)
				return m.getKey();
		return -1;
	}

一种比較巧妙的办法是使用异或,由于同样的元素经过异或运算后就变成了0。

	public int singleNumber(int[] A) {
		int temp = 0;
		for(int i=0;i<A.length;i++)
			temp ^= A[i];
		return temp;
	}
比方:传入{2,2,4,3,3}。计算步骤例如以下:

temp = 0 A[0]=2
temp = 2
------------------
temp = 2 A[1]=2
temp = 0
------------------
temp = 0 A[2]=4
temp = 4
------------------
temp = 4 A[3]=3
temp = 7
------------------
temp = 7 A[4]=3
temp = 4

posted on 2017-07-21 19:26  cynchanpin  阅读(165)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3