File tree Expand file tree Collapse file tree 1 file changed +25
-1
lines changed
Leetcode/leetcodeTags/array Expand file tree Collapse file tree 1 file changed +25
-1
lines changed Original file line number Diff line number Diff line change 11package leetcodeTags .array ;
22
33import java .util .Arrays ;
4+ import java .util .HashMap ;
45
56public class TwoSum1 {
67
7- public static int [] twoSum (int [] nums , int target ) {
8+ public static int [] twoSum2 (int [] nums , int target ) {
89
910 if (nums .length < 2 )
1011 return null ;
@@ -30,6 +31,29 @@ public static int[] twoSum(int[] nums, int target) {
3031 return ans ;
3132 }
3233
34+ public static int [] twoSum (int [] nums , int target ) {
35+
36+ int [] ans = new int [2 ];
37+
38+ // number and index
39+ HashMap <Integer , Integer > map = new HashMap <>();
40+
41+ for (int index = 0 ; index < nums .length ; index ++) {
42+
43+ if (!map .containsKey (nums [index ])) {
44+
45+ map .put (target - nums [index ], index );
46+
47+ } else {
48+ ans [0 ] = index ;
49+ ans [1 ] = map .get (nums [index ]);
50+ break ;
51+ }
52+ }
53+
54+ return ans ;
55+ }
56+
3357 public static void main (String [] args ) {
3458 int [] nums = { 2 , 7 , 11 , 15 };
3559 int target = 9 ;
You canβt perform that action at this time.
0 commit comments