leetcode之Single Number
2016-04-26 18:50
357 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">LeetCode官网网址:https://leetcode.com</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">本题网址:https://leetcode.com/problems/single-number/</span>
题目:
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?
Subscribe to see which companies asked this question
题目大概意思就是找出这个数组中只出现一次而不是两次的数。本题要求时间复杂度为线性时间,并且不以增加内存来实现。
于是,有一种比较好的思路就是采用集合,将遇到的数字加进集合,当再次遇到时从集合中删掉这个数字,循环结束后,剩下的那个数就是答案。
嗯,上代码:
public class Solution { public int singleNumber(int[] nums) { HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { if (set.isEmpty()) set.add(nums[i]); else if (set.contains(nums[i])) set.remove(nums[i]); else set.add(nums[i]); } Iterator<Integer> iterator = set.iterator(); Integer result = 0; while (iterator.hasNext()) { result = iterator.next(); } return result; } }
相关文章推荐
- iOS开发-你真的会用SDWebImage?(转发)
- mybatis中$和#区别
- swift2.0 学习笔记Three
- CAAnimation--CALayer
- 每日Scrum(8)
- 【ZOJ3947 The 13th Zhejiang Provincial Collegiate Programming ContestL】【水题】Very Happy Great BG 简单求和
- B树
- Win7/Win8/Win8.1/Win10下的DragEnter DragDrop事件不触发
- 使用i3wm时出现的若干问题的解决办法
- 【ZOJ3946 The 13th Zhejiang Provincial Collegiate Programming ContestK】【最短路+贪心 or 最小树形图】Highway Proje
- (独家)Linux邮件报警神器 mutt
- 【ZOJ3944 The 13th Zhejiang Provincial Collegiate Programming ContestI】【简单模拟】People Counting 照片人数统计 人
- 如何为Android缓存数据到本地
- eclipse maven tomcat7 热部署
- VC2008下使用OpenSSL 1.0.0g(免编译)
- 解决Android TextView默认的padding问题
- #学习笔记#(60)从零开始学习Nodejs[2]——用Telnet发送数据到Node TCP服务器
- 跨平台编程中的宏定义(__LINE__和__DATE__极其有用)
- 站立会议第八天
- 微信打开网址添加在浏览器中打开提示