Skip to content

Instantly share code, notes, and snippets.

@fakruboss
Last active August 3, 2023 14:55
Show Gist options
  • Save fakruboss/14595d945045ae21f0dc1d57ee9741f6 to your computer and use it in GitHub Desktop.
Save fakruboss/14595d945045ae21f0dc1d57ee9741f6 to your computer and use it in GitHub Desktop.
# METHOD 1 : using map
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numVsIndex = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
int rem = target - nums[i];
if (numVsIndex.containsKey(rem)) {
return new int[]{i, numVsIndex.get(rem)};
}
numVsIndex.put(nums[i], i);
}
return new int[]{-1, -1};
}
}
# METHOD 2 : using 2 for loops
class Solution {
public int[] twoSum(int[] nums, int target) {
int size = nums.length;
int[] ans = new int[2];
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target) {
ans[0] = i;
ans[1] = j;
return ans;
}
}
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment