Two Sum

less than 1 minute read

This program was created to take in an array of numbers and returns the position of the numbers that add up to the target.

The code has been modified slightly and now uploaded to the site.

<— Return Home

Solution.java

import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        // int[] nums = {2, 7, 11, 15};
        // int target = 9;
        // int[] nums = {3, 2, 4};
        // int target = 6;
        int[] nums = {3, 3};
        int target = 6;
        int[] result = twoSum(nums, target);
        System.out.println(Arrays.toString(result));
    }

    public static int[] twoSum(int[] nums, int target){
        int[] output = new int[2];
        for (int i = 0; i < nums.length; i++){
            for (int j = i + 1; j < nums.length; j++){
                if (nums[i] + nums[j] == target){
                    output[0] = i;
                    output[1] = j;
                }
            }
        }
        return output;
    }
}

<— Return Home