Blind 75
Two Sum
- Problem
- LC 1
- Category
- Array
- File
- blind75_LC1TwoSum.java
- Path
- pkg5leetcode/blind75/blind75_LC1TwoSum.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC1TwoSum.java
- Lesson
- Back to the chapter
- Approach
- One-pass hash map stores value->index; check complement each step.
- Complexity
- Time O(n), Space O(n)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Two Sum | LC 15 * APPROACH: One-pass hash map stores value->index; check complement each step.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class blind75_LC1TwoSum {11 static int[] twoSum(int[] nums, int target) {12 Map<Integer, Integer> seen = new HashMap<>();13 for (int i = 0; i < nums.length; i++) {14 int need = target - nums[i];15 if (seen.containsKey(need)) return new int[]{seen.get(need), i};16 seen.put(nums[i], i);17 }18 return new int[]{-1, -1};19 }20 21 public static void main(String[] args) {22 check(Arrays.equals(twoSum(new int[]{2, 7, 11, 15}, 9), new int[]{0, 1}), "case1");23 check(Arrays.equals(twoSum(new int[]{3, 2, 4}, 6), new int[]{1, 2}), "case2");24 System.out.println("all tests passed");25 }26 27 static void check(boolean cond, String name) {28 if (!cond) throw new AssertionError("FAILED: " + name);29 System.out.println(" PASS " + name);30 }31}