Skip to content

Commit 1560711

Browse files
committed
add solution of problem 260: single number iii
1 parent 6dd827c commit 1560711

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

SingleNumberIII260/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
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.
2+
3+
For example:
4+
5+
Given nums = `[1, 2, 1, 3, 2, 5]`, return `[3, 5]`.
6+
7+
#####Note:
8+
1. The order of the result is not important. So in the above example, `[5, 3]` is also correct.
9+
2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

SingleNumberIII260/Solution.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
public class Solution {
2+
public int[] singleNumber(int[] nums) {
3+
int[] result = new int[2];
4+
if (nums == null || nums.length == 0)
5+
return result;
6+
7+
int xorResult = nums[0];
8+
for (int i = 1; i < nums.length; i++)
9+
xorResult ^= nums[i];
10+
11+
int partitionNum = xorResult & (xorResult ^ (xorResult - 1));
12+
List<List<Integer>> twoParts = partition(nums, partitionNum);
13+
result[0] = singleNumberOneValue(twoParts.get(0));
14+
result[1] = singleNumberOneValue(twoParts.get(1));
15+
16+
return result;
17+
}
18+
19+
private List<List<Integer>> partition(int[] nums, int partitionNum) {
20+
List<List<Integer>> result = new ArrayList<List<Integer>>();
21+
List<Integer> partOne = new ArrayList<Integer>();
22+
List<Integer> partTwo = new ArrayList<Integer>();
23+
24+
for (int i = 0; i < nums.length; i++) {
25+
if ((nums[i] & partitionNum) == 0)
26+
partOne.add(nums[i]);
27+
else
28+
partTwo.add(nums[i]);
29+
}
30+
31+
result.add(partOne);
32+
result.add(partTwo);
33+
34+
return result;
35+
}
36+
37+
private int singleNumberOneValue(List<Integer> nums) {
38+
int result = 0;
39+
Iterator<Integer> iter = nums.iterator();
40+
while (iter.hasNext())
41+
result ^= iter.next();
42+
return result;
43+
}
44+
}

0 commit comments

Comments
 (0)