> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/master.md).

# 09/14/2021 No.2 Two sum

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*****&#x20;one solution**, and you may not use the *same* element twice.

You can return the answer in any order.

Brutal force:

class Solution {&#x20;

&#x20;      public int\[] twoSum(int\[] nums, int target) {

```
   if (nums == null || nums.length < 2){
       return null;
   }

   for (int i = 0; i < nums.length; i++){
       for (int j = i +1; i < nums.length; j++){
           if (nums[i] + nums[j] == target){
               return new int[]{i , j};
           }
       }
   }
    return null;
```

&#x20;   }&#x20;

}

**Optimized way: using hashMap,**&#x20;

map.containsKey(n) return the key;

map.put (value, key);

map.get(value) => to get the key.

\==========================================================================

class Solution {&#x20;

&#x20;  public int\[] twoSum(int\[] nums, int target) {

```
   if (nums == null || nums.length < 2){
       return null;
   }

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

&#x20;      }&#x20;

}
