---
# System prepended metadata

title: Leetcode 1.Two Sum
tags: [Hash Table]

---

# Leetcode 1.Two Sum
# HashMap、Map

> https://www.runoob.com/java/java-hashmap.html
> https://www.delftstack.com/zh-tw/howto/java/difference-between-hashmap-and-map-in-java/

faster than 99.96%

時間複雜度: O(n)
空間複雜度: O(n)

``` java=

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // HashMap=>key、value去對應，藉此快速找出符合的條件     
        // key type , value type
        Map<Integer,Integer> map= new HashMap<>();
        
        for(int i=0;i<nums.length;i++){
            if(map.get(target-nums[i])!=null){
                return new int[]{map.get(target-nums[i]),i};
            }
            map.put(nums[i],i);
        }
        
        // 因型態是int[]，故回傳null，不能回傳0(int)
        return null;
    }
}        

```
###### tags: `Hash Table`