- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsingle_number_ii.dart
87 lines (60 loc) · 1.5 KB
/
single_number_ii.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
-* 137. Single Number II *-
Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Constraints:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
Each element in nums appears exactly three times except for one element which appears once.
*/
import'dart:collection';
classA {
intsingleNumber(List<int> nums) {
HashMap<int, int> map =HashMap<int, int>();
for (int x in nums) {
map[x] = (map[x] ??0) +1;
}
for (MapEntry entry in map.entries) {
if (entry.value ==1) {
return entry.key;
}
}
return-1;
}
}
classB {
intsingleNumber(List<int> nums) {
int ans =0;
for (int i =0; i <32; ++i) {
int sum =0;
for (finalint number in nums) {
sum += (number >> i) &1;
}
sum %=3;
ans |= (sum << i);
}
// Handle negative numbers
if ((ans & (1<<31)) !=0) {
ans =-(1<<31) | (ans & ((1<<31) -1));
}
return ans;
}
}
classC {
intsingleNumber(List<int> nums) {
int ones =0;
int twos =0;
for (int i =0; i < nums.length; i++) {
finalint number = nums[i];
ones ^= (number &~twos);
twos ^= (number &~ones);
}
return ones;
}
}