Single Number II – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
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.
C++ Single Number II LeetCode Solution
class Solution {
public:
int singleNumber(vector& nums) {
if(nums.size()==1) return nums[0];
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++)
{
int count=1;
while(i<nums.size()-1 and nums[i]==nums[i+1]){i++;count++;}
if(count==1) return nums[i];
}
return 0;
}
};
Java Single Number II LeetCode Solution
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int num : nums) {
map.put(num,map.getOrDefault(num, 0)+1);
}
int result = 0;
for (Map.Entry<Integer,Integer> entry : map.entrySet())
{
if(entry.getValue()==1)
result = entry.getKey();
}
return result;
}
}
Python 3 Single Number II LeetCode Solution
class Solution:
# approach 1
def singleNumber(self, nums: List[int]) -> int:
one,two=0,0
for i in nums:
one=~two&(one^i)
two=~one&(two^i)
return one
# approach 2
def singleNumber(self, nums: List[int]) -> int:
d={}
for i in nums:
if i in d:
d[i]+=1
else:
d[i]=1
for k,v in d.items():
if v==1:
return k
return -1
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1
Leave a comment below