Published in

# LeetCode: 1.Two Sum (Java)

Given an array of integers `nums` and an integer `target`, return 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.

# Solution 1: 暴力二層迴圈

`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};                }            }        }        return new int[0];    }}`

Runtime: 0 ms, faster than 100.00%

Memory Usage: 38.9 MB, less than 92.80%

# Solution 2: HashMap方式

`class Solution {    public int[] twoSum(int[] nums, int target) {        HashMap m = new HashMap<Integer, Integer>(nums.length);        for (int i = 0; i < nums.length; i++) {            int t = target - nums[i];            if (m.containsKey(t)) {                return new int[]{i, (int) m.get(t)};            }            m.put(nums[i], i);        }        throw new IllegalArgumentException("error");    }}`

Runtime: 0 ms, faster than 100.00%

Memory Usage: 39 MB, less than 79.44%

--

--