Skip to main content

LeetCode 1: Two Sum in Java

· One min read
Apache Wangye
Software developer and technical writer

Given an integer array nums and an integer target, return the indexes of two distinct elements whose sum equals the target.

Brute force

class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No solution");
}
}

Time complexity is O(n²) and extra space is O(1).

One-pass HashMap

For each value, calculate the required complement and check whether it has already been seen:

import java.util.HashMap;
import java.util.Map;

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> indexByValue = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (indexByValue.containsKey(complement)) {
return new int[]{indexByValue.get(complement), i};
}
indexByValue.put(nums[i], i);
}

throw new IllegalArgumentException("No solution");
}
}

Average time complexity is O(n) and space complexity is O(n). Checking before inserting prevents the current element from matching itself and correctly handles inputs such as [3, 3] with target 6.

Page views: --

Total views -- · Visitors --