[LeetCode]:Single Number III
2015-12-13 17:34
246 查看
Describe
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Input
Output
Analyse
自己写的算法是用LinkedList来做的,然后一层循环,如果当前nums[i]在LinkedList里面,那么说明这个数是重复的,所以就将这个数从List里面移除,反之就将数加入到List里面,最后List里面剩余的就是那两个只出现一次的数。(⊙v⊙)嗯,怎么说呢,这是正常的逻辑,然后运行也通过了,然后一看时间是505ms,有点慢了,应该是java的原因吧,看看别人的时间吧,哦,2ms!!!
我待算法如初恋,算法虐我千百遍!
Code
自己的就不拿出来了,看看大神的吧%>_<%
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Input
nums = [1, 2, 1, 3, 2, 5]
Output
[3, 5]
Analyse
自己写的算法是用LinkedList来做的,然后一层循环,如果当前nums[i]在LinkedList里面,那么说明这个数是重复的,所以就将这个数从List里面移除,反之就将数加入到List里面,最后List里面剩余的就是那两个只出现一次的数。(⊙v⊙)嗯,怎么说呢,这是正常的逻辑,然后运行也通过了,然后一看时间是505ms,有点慢了,应该是java的原因吧,看看别人的时间吧,哦,2ms!!!
我待算法如初恋,算法虐我千百遍!
Code
自己的就不拿出来了,看看大神的吧%>_<%
public class Solution{ public int[] singleNumber(int[] nums){ int diff = 0; for (int num : nums){ diff ^= num; } diff &= -diff; int[] rets = {0, 0}; for (int num : nums) { if ((num & diff) == 0) rets[0] ^= num; else rets[1] ^= num; } return rets; } }
相关文章推荐
- Node.js实战(1)
- 铺垫一个 数据类型
- Person Re-identification Datasets
- 关于NestableRuntimeException异常的解决
- RecyclerView的事件监听
- mysql修改表alter小结
- Java 多线程(四)线程间的通信jdk1.5中Lock,Condition----各种锁的相关详细概念
- 菜鸟学习Hibernate——简单的增、删、改、查操作
- onvif学习笔记2:了解onvif
- MTK RF参数写入代码操作步骤 (2012-09-25 11:43:10)
- NSURLSessionConfiguration的简单实用
- GBDT(MART) 迭代决策树入门教程 | 简介
- 可与教科书相媲美的书——《世界是数字的》
- 简单的ajax让前端jquery与后台node.js交互
- innodb_buffer_pool特性和参数调整学习
- Photo Editing Extension 详解 (附带应用滤镜Demo)
- 【转】三种不同类型的ssh隧道
- maven编译,控制台中文乱码解决方案
- Synchroniazed和Lock实现生产者--消费者
- 批量修改文件名和后缀名的python设计