260. Single Number III
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了260. Single Number III相关的知识,希望对你有一定的参考价值。
260. Single Number III
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.
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?
上两个的升级版,但是跟上两个思路又完全不同。真是。。。
两种做法,一个位运算肯定是技巧性很高的,一个是set维护。
Java set做法:
遍历这个数组,第一次出现的添加进去,只要出现了第二次,则remove,剩下的就是单个了的数集合了,也适用用于找出数组中成对出现数中的所有单个数。最后把这个set集合元素添到数组就行了。
查了资料,貌似不能直接把一个set集合转换成Array,toArray也只能装换成object,参考可见:https://ask.helplib.com/106360。
public class Solution { public int[] singleNumber(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int n : nums) { if(!set.contains(n)) { set.add(n); }else { set.remove(n); } } int[] ans = new int[set.size()]; int cnt = 0; for(int n:set) { ans[cnt++] = n; } return ans; } }
位运算做法:
以上是关于260. Single Number III的主要内容,如果未能解决你的问题,请参考以下文章