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?
之前为Question136写的代码没有通过,因为我使用了额外的内存,但是这个题目允许使用,所以派上用场了。public class Solution { public int[] singleNumber(int[] nums) { List<Integer> list=new ArrayList<>(); int[] res=new int[2]; for(int i=0;i<nums.length;i++) { if(list.contains(nums[i])==true) { list.remove(list.indexOf(nums[i])); } else { list.add(nums[i]); } } for(int i=0;i<list.size();i++) { res[i]=list.get(i); } return res; } }