---
# System prepended metadata

title: \#1 Two Sum 兩數之合
tags: [leetcode, leetcode-easy]

---

# \#1 Two Sum 兩數之合
## *給定陣列和target, 回傳陣列中兩數和=target的index*

 - [ ] 改善:用兩數之差可以更節省loop C演算，複雜度從N平方降為N
    ```javascript
    var twoSum = function(nums, target) {
        var a = {}
        var ret = []
        for(var i=0; i<nums.length; i++){
            var diff = target - nums[i]
            if(typeof(a[diff]) !== 'undefined'){
                ret.push(i)
                ret.push(nums.indexOf(diff))
                return ret
            }
            a[nums[i]] = diff
        }
    };
    ```

 - [ ] 初見:跑loop判斷陣列中每個元素和是否等同target，loog跑法為排列組合中的C(即CX取2，X為target.length)
    ```javascript
    var twoSum = function(nums, target) {
        var t_ret = [];
        for(var i=0;i<nums.length;i++){
            for(var j=i+1;j<nums.length;j++){
                if(nums[i]+nums[j]===target){
                    t_ret.push(i);t_ret.push(j);
                    break;
                }
            }
        }
        return t_ret;
    };
    ```
    test

###### tags: `leetcode`, `leetcode-easy`