File tree Expand file tree Collapse file tree 1 file changed +18
-1
lines changed
Leetcode/leetcodeTags/array Expand file tree Collapse file tree 1 file changed +18
-1
lines changed Original file line number Diff line number Diff line change @@ -54,10 +54,27 @@ public static int[] twoSum(int[] nums, int target) {
5454 return ans ;
5555 }
5656
57+ public static int [] twoSum3 (int [] nums , int target ) {
58+
59+ HashMap <Integer , Integer > map = new HashMap <>();
60+
61+ for (int index = 0 ; index < nums .length ; index ++) {
62+
63+ int targetSum = target - nums [index ];
64+
65+ if (map .containsKey (targetSum )) {
66+ return new int [] { index , map .get (targetSum ) };
67+ } else {
68+ map .put (nums [index ], index );
69+ }
70+ }
71+ return new int [2 ];
72+ }
73+
5774 public static void main (String [] args ) {
5875 int [] nums = { 2 , 7 , 11 , 15 };
5976 int target = 9 ;
6077
61- System .out .println (Arrays .toString (twoSum (nums , target )));
78+ System .out .println (Arrays .toString (twoSum3 (nums , target )));
6279 }
6380}
You canβt perform that action at this time.
0 commit comments