136. Single Number
Description
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?
Constraints
Approach
Links
YouTube
Examples
Input: [2, 2, 1]
Output: 1
Solutions
/**
* Time complexity : O(n*1) = O(n). Time complexity of for loop is O(n).
* Time complexity of hash table(dictionary in python) operation pop is O(1).
* Space complexity : O(n). The space required by hash_table is equal to the
* number of elements in nums.
*/
class Solution {
public int singleNumber(int[] nums) {
if(nums.length == 1) return nums[0];
int value = 0;
if(nums.length%2 == 0) return value;
Map<Integer, Integer> values = new HashMap();
for(int n: nums) {
values.put(n, values.getOrDefault(n, 0)+1);
}
for(int n: nums) {
if(values.get(n) == 1) {
return n;
}
}
return value;
}
}
Follow up
Last updated
Was this helpful?