Dare2Solve
Given an array of integers, return the indices of the two numbers that add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
We can use a hashmap to store the complement of each number. As we iterate through the array, we check if the current number's complement exists in the hashmap.
O(n), where n is the length of the array.
O(n), for the hashmap.
class Solution {
public:
int singleNumber(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
if (find(nums.begin(), nums.end(), nums[i]) == find(nums.rbegin(), nums.rend(), nums[i]).base() - 1) {
return nums[i];
}
}
return -1; // Should never reach here since the problem guarantees a solution
}
};
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result
class Solution {
public int singleNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[i] == nums[j]) {
count++;
}
}
if (count == 1) {
return nums[i];
}
}
return -1; // If no single number found
}
}
var singleNumber = function (nums) {
for (let i = 0; i < nums.length; i++) {
if (nums.indexOf(nums[i]) === nums.lastIndexOf(nums[i])) {
return nums[i];
}
}
};