136. Single Number
Approach 1: List operation
Algorithm
- Iterate over all the elements in
nums
- If some number in
nums
is new to array, append it - If some number is already in the array, remove it
Implementation
class Solution {
public int singleNumber(int[] nums) {
List<Integer> no_duplicate_list = new ArrayList<>();
for (int i : nums) {
if (!no_duplicate_list.contains(i)) {
no_duplicate_list.add(i);
} else {
no_duplicate_list.remove(new Integer(i));
}
}
return no_duplicate_list.get(0);
}
}
Java
class Solution {
public int singleNumber(int[] nums) {
List<Integer> no_duplicate_list = new ArrayList<>();
for (int i : nums) {
if (!no_duplicate_list.contains(i)) {
no_duplicate_list.add(i);
} else {
no_duplicate_list.remove(new Integer(i));
}
}
return no_duplicate_list.get(0);
}
}
Python
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
no_duplicate_list = []
for i in nums:
if i not in no_duplicate_list:
no_duplicate_list.append(i)
else:
no_duplicate_list.remove(i)
return no_duplicate_list.pop()
Complexity Analysis
- Time complexity : . We iterate through
nums
, taking time. We search the whole list to find whether there is duplicate number, taking time. Because search is in thefor
loop, so we have to multiply both time complexities which is . - Space complexity : . We need a list of size to contain elements in
nums
.