[LeetCode] Single Number III ( a New Questions Added today)
2015-08-17 15:49
127 查看
Given an array of numbers
For example:
Given
Note:
The order of the result is not important. So in the above example,
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
这是今天刚加上去的一道题。
个人觉得这道题和之前single number的两道差不多。依旧用hashset即可做出。
唯一要注意的就是最后return的时候不能直接return hashset。为了偷懒我直接弄了个新的int[]。
代码如下。~
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.
For example:
Given
nums = [1, 2, 1, 3, 2, 5], return
[3, 5].
Note:
The order of the result is not important. So in the above example,
[5, 3]is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
这是今天刚加上去的一道题。
个人觉得这道题和之前single number的两道差不多。依旧用hashset即可做出。
唯一要注意的就是最后return的时候不能直接return hashset。为了偷懒我直接弄了个新的int[]。
代码如下。~
public class Solution { public int[] singleNumber(int[] nums) { if(nums.length==2&&nums[0]!=nums[1]){ return nums; } HashSet<Integer> store=new HashSet<Integer>(); HashSet<Integer> result=new HashSet<Integer>(); for(int i=0;i<nums.length;i++){ if(!result.add(nums[i])){ result.remove(nums[i]); store.add(nums[i]); }else{ if(store.contains(nums[i])){ result.remove(nums[i]); } } } int[] print=new int[2]; print[0]=result.iterator().next(); result.remove(result.iterator().next()); print[1]=result.iterator().next(); return print; } }
相关文章推荐
- android studio 新建项目 界面一直停在 【“building ‘ 项目名’ gradle project info”】
- UITableView使用详解
- [Leetcode] Longest Consecutive Sequence
- ZOJ 3210 A Stack or A Queue ? 水
- HDFS列式存储Parquet与行式存储(Avro)性能测试-Benchmark(hadoop, Spark, Scala)
- 【CF 570D】Tree Requests
- IOS UItableView得到group如何摆脱的剪裁线条样式问题
- request 和 response 的页面跳转
- POJ_3080_BlueJeans
- That Nice Euler Circuit (好看的一笔画)
- C#子线程中更新ui
- HDU 1711 — Number Sequence简单题
- UVA_10534_WavioSequence
- Refresh Global Unique Identifiers (GUIDs)
- iOS7对UITableViewCell的层级改变
- Ahui Writes Word
- Ahui Writes Word
- MySQL 一般查询日志(General Query Log)
- Android GUI之View布局
- HDU_2227_FindTheNondecreasingSubsequences