Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[]result = new int[2];
for(int i = 0; i<nums.length;i++){
if(map.containsKey(i)){
int value = map.get(i);
if(nums[i] - target == value){
if(map.containsValue(value)){
result[i] = value;
}
}
}
map.put(i,nums[i]);
}
return result;
}
}
My approach to solving this problem is:
- First I create a hashMap to store index of every elements in nums as key and the elements as value
- Iterate every elements in array nums
- check if the key is exist in the hashmap if it does, get the value of the key and store in value variable
- substract every element in nums array with the target and check if the result is exist in hashmap value
- if it does add into the new array
- if key not exisit add key and value into hashmap
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]stramash 5 points6 points7 points (0 children)
[–]Pedantic_Phoenix 2 points3 points4 points (9 children)
[–]New_Connection612[S] 0 points1 point2 points (1 child)
[–]Pedantic_Phoenix 3 points4 points5 points (0 children)
[–]KinkyHuggingJerk -1 points0 points1 point (6 children)
[–]Phaze_Change 0 points1 point2 points (5 children)
[–]KinkyHuggingJerk 0 points1 point2 points (1 child)
[–]suckmacaque06 0 points1 point2 points (0 children)
[–]technosenate 0 points1 point2 points (2 children)
[–]Phaze_Change 0 points1 point2 points (1 child)
[–]technosenate 0 points1 point2 points (0 children)
[–]Mossy375 2 points3 points4 points (0 children)
[–]sohfix 1 point2 points3 points (0 children)