Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
Approach #1: C++.
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> mp;
for (int i = 0; i < nums.size(); ++i)
mp[nums[i]]++;
for (int i = 0; i < nums.size(); ++i)
if (mp[nums[i]] == 1) return nums[i];
}
};
Approach #2: Java.
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int i : nums)
result ^= i;
return result;
}
}
Note: ^ return 0 if two elements is same.
Approach #3: Python.
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for num in nums:
dic[num] = dic.get(num, 0) + 1
for key, val in dic.items():
if val == 1:
return key
The dictionary get method:
Description
The method get() returns a value for the given key. If key is not available then returns default value None.
Syntax
Following is the syntax for get() method −
dict.get(key, default = None)
Parameters
-
key − This is the Key to be searched in the dictionary.
-
default − This is the Value to be returned in case key does not exist.
Return Value
This method return a value for the given key. If key is not available, then returns default value None.
Time Submitted | Status | Runtime | Language |
---|---|---|---|
a few seconds ago | Accepted | 36 ms | python |
2 minutes ago | Accepted | 1 ms | java |
5 minutes ago | Accepted | 12 ms | cpp |