Skip to content

Instantly share code, notes, and snippets.

@ghadj
Created June 9, 2025 10:53
Show Gist options
  • Select an option

  • Save ghadj/98d7f63102a8484c086f9bb8e0573c12 to your computer and use it in GitHub Desktop.

Select an option

Save ghadj/98d7f63102a8484c086f9bb8e0573c12 to your computer and use it in GitHub Desktop.
Leetcode - Two Sum
/**
* ---
* [https://leetcode.com/problems/two-sum]
* Two Sum
* 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.
* ---
*
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(nums.length);
int i, current, complement;
for (i = 0; i < nums.length; i++) {
current = nums[i];
complement = target - current;
if (map.containsKey(complement))
return new int[] {i, map.get(complement)};
map.put(current, i);
}
return new int[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment