Last active
August 3, 2023 14:55
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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