File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Problem: https://leetcode.com/problems/two-sum/
3
+ Description: return indices of the two numbers such that they add up to target. not use the same element twice.
4
+ Topics: Array, Hash Table
5
+ Time Complexity: O(N), Runtime 2ms
6
+ Space Complexity: O(N), Memory 45.1MB
7
+ */
8
+ class Solution {
9
+ public int [] twoSum (int [] nums , int target ) {
10
+ Map <Integer , Integer > numIndex = new HashMap <>();
11
+ for (int secondIndex =0 ; secondIndex <nums .length ; secondIndex ++){
12
+ if (numIndex .containsKey (target -nums [secondIndex ])){
13
+ int firstIndex = numIndex .get (target -nums [secondIndex ]);
14
+ return new int []{firstIndex , secondIndex };
15
+ } else {
16
+ numIndex .put (nums [secondIndex ], secondIndex );
17
+ }
18
+ }
19
+ return new int []{};
20
+ }
21
+ }
You can’t perform that action at this time.
0 commit comments