Skip to content

Instantly share code, notes, and snippets.

@iHaikal
Created May 28, 2019 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iHaikal/8957484034bcf09609f9d17cbc6e2daa to your computer and use it in GitHub Desktop.
Save iHaikal/8957484034bcf09609f9d17cbc6e2daa to your computer and use it in GitHub Desktop.
a submitted solution to TwoSums problem in Leetcode
// problem: https://leetcode.com/problems/two-sum/
import java.util.HashMap;
class Solution {
int[] twoSum(int[] nums, int target){
int firstIndex = -1, secondIndex = -1;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length;i++){
map.put(target - nums[i], i);
}
for (int i = 0; i < nums.length;i++){
if (!map.containsKey(nums[i])) continue;
int cur = map.get(nums[i]);
if (nums[cur] + nums[i] == target && cur != i){
firstIndex = i;
secondIndex = cur;
break;
}
}
// can be removed at submission
if (firstIndex == -1){
return null;
}
return new int[]{firstIndex, secondIndex};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment