[📝LeetCode #1] Two Sum
shine

shine @shine7on

About: Japanese girl who wants to improve her coding

Joined:
May 30, 2025

[📝LeetCode #1] Two Sum

Publish Date: Jun 29
0 0

🎀 The Problem

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]

👩‍💻 My Answer

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int index = 0;

        while(index < nums.length){
            for (int i = index+1; i < nums.length; i++) {
                if (nums[i] == target - nums[index]) {
                    int[] output = new int[2];
                    output[0] = index;
                    output[1] = i;
                    return output;
                }
            }
            index++;
        }

        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

Pro & Con

  • ✖️ Runtime & Memory
  • ✖️ Brute Force Code (nested loop)

💋 Ideal Answer

Approach - "Hash Table"

I read the solution on LeetCode and found that using a hash table is the fastest one for this.

New Code

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

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

        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

New Runtime & Memory

💡 What I Learned

  • How I construct int[] in return line return new int[] {map.get(target - nums[i]),i};

Comments 0 total

    Add comment