Created
May 28, 2019 01:57
-
-
Save iHaikal/8957484034bcf09609f9d17cbc6e2daa to your computer and use it in GitHub Desktop.
a submitted solution to TwoSums problem in Leetcode
This file contains hidden or 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
// 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