MCPcopy Create free account
hub / github.com/B-Rajagopalan/CodingAtti-YouTube / TwoSum

Class TwoSum

Leetcode-InterviewQuestions/src/Easy/TwoSum.java:6–43  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4import java.util.HashMap;
5
6public class TwoSum {
7 public static void main(String[] args) {
8 int[] nums = {3, 2, 4};
9 int target = 6;
10 System.out.println(Arrays.toString(twoSumOptimized(nums, target)));
11 }
12
13 //brute force
14 public static int[] twoSum(int[] nums, int target) {
15 int[] result = new int[2];
16 for (int i = 0; i < nums.length - 1; i++) {
17 for (int j = i + 1; j < nums.length; j++) {
18 if (nums[i] + nums[j] == target) {
19 result[0] = i;
20 result[1] = j;
21 return result;
22 }
23 }
24 }
25 return result;
26 }
27
28 //optimized
29 public static int[] twoSumOptimized(int[] nums, int target) {
30 int[] result = new int[2];
31 HashMap<Integer, Integer> check = new HashMap<>();
32 for (int i = 0; i < nums.length; i++) {
33 int sum = target - nums[i];
34 if (check.containsKey(sum)) {
35 result[0] = i;
36 result[1] = check.get(sum);
37 return result;
38 }
39 check.put(nums[i], i);
40 }
41 return result;
42 }
43}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected