【Leetcode】Single Number
2015-11-30 22:05
267 查看
题目链接:https://leetcode.com/problems/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?
思路:
1、用HashMap,时间复杂度O(n),空间复杂度O(n)
2、用位操作,考虑异或的特点:x^x=0,异或满足结合律和交换律,0^x=x。
对数组所有元素异或一次,即n[0]^n[1]^n[2].....运用交换律和结合律可以把相同元素放一起异或结果为0,而0和剩余元素异或不会改变结果,所以
最后得到结果 为出现次数为奇数的元素。空间复杂度为O(1)。
算法1:
算法2:
题目:
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?
思路:
1、用HashMap,时间复杂度O(n),空间复杂度O(n)
2、用位操作,考虑异或的特点:x^x=0,异或满足结合律和交换律,0^x=x。
对数组所有元素异或一次,即n[0]^n[1]^n[2].....运用交换律和结合律可以把相同元素放一起异或结果为0,而0和剩余元素异或不会改变结果,所以
最后得到结果 为出现次数为奇数的元素。空间复杂度为O(1)。
算法1:
public int singleNumber(int[] nums) { Map<Integer, Integer> maps = new HashMap<Integer, Integer>(); for (int i : nums) { if (maps.containsKey(i)) { maps.remove(i); } else { maps.put(i, 1); } } return (int) maps.keySet().toArray()[0]; }
算法2:
public int singleNumber(int[] nums) { int result = 0; for (int i = 0; i < nums.length; i++) { result ^= nums[i]; } return result; }
相关文章推荐
- JSP取得绝对路径
- hibernate set集合配置排序
- JAVAEE 企业网站建设发布与网站备案流程
- mac安装命令行
- 关于php COOKIE和SESSION的一些理解
- Qt Creator在windows平台下显示中文问题
- R-store
- 菜鸟好文推荐(二十六)——避免Java堆空间错误的5个步骤
- extjs中去掉form表单标签后面的冒号
- Spark MLlib logistic回归案例
- 容器总结——关联式容器
- Javaweb邮箱验证注册的实现
- Delphi 的接口机制——接口操作的编译器实现过程(2)
- 二、C++多态性
- mysql中导入txt文件数据的操作指令
- 线性表排序(C语言版)
- Delphi 的接口机制——接口操作的编译器实现过程(1)
- LeetCode题解 #7 Reverse Integer
- Beta版本冲刺———第一天
- tmux 窗口自动变更名字