Source Link:
https://leetcode.com/problems/two-sum/description/
Question:
Given an array of integers, return indices of the two numbers such that they 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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
My Solution:
Note:
1. Using HashMap:
HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
2. Put the number as "key", and its index as "value"
hashmap.put(nums[i], i);
3. We are looking for another number that is equal to "target - nums[i]"
int another = target - nums[i];
4. if we can find another_number and another_number is not itself
if(hashmap.containsKey(another) && (int)hashmap.get(another) !=i)
No comments:
Post a Comment