leetcode-pp / 91alg-6-daily-check

91 算法第六期打卡仓库
28 stars 0 forks source link

【Day 19 】2021-12-30 - 两数之和 #26

Open azl397985856 opened 2 years ago

azl397985856 commented 2 years ago

两数之和

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/two-sum

前置知识

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

yan0327 commented 2 years ago

思路: 两数之和,梦开始的地方。哈希表

func twoSum(nums []int, target int) []int {
    hash := map[int]int{}
    for i,x := range nums{
        if out,ok := hash[target-x];ok{
            return []int{out,i}
        }else{
            hash[x] = i
        }
    }
    return nil
}

时间复杂度O(n) 空间复杂度O(n)

yetfan commented 2 years ago

思路 今天又没k到第一 TUT

代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        gaps = dict()
        for i, num in enumerate(nums):
            if target - num in gaps:
                return [i, gaps[target - num]]
            gaps[num] = i
        return []

复杂度 时间 O(n) 空间 O(n)

Arya-03 commented 2 years ago
def twoSum(nums, target):
    lens = len(nums)
    j=-1
    for i in range(lens):
        if (target - nums[i]) in nums:
            if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):#如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
                continue
            else:
                j = nums.index(target - nums[i],i+1) #index(x,i+1)是从num1后的序列后找num2                
                break
    if j>0:
        return [i,j]
    else:
        return []
wxj783428795 commented 2 years ago

思路

  1. 遍历数组,用一个哈希表储存值和下标
  2. 当哈希表中没有以当前值为key的值时,将target-当前值,作为key,下标作为value,存入哈希表
  3. 下次循环,如果哈希表中有以当前值为key,则说明,已经找到两个元素,下标就是哈希表中储存的下标,和当前的i

代码

var twoSum = function (nums, target) {
    let obj = {};
    for (let i = 0; i < nums.length; i++) {
        let num = nums[i];
        if (obj[num] === undefined) {
            obj[target - num] = i;
        } else {
            return [obj[num], i]
        }
    }
};

复杂度分析

复杂度分析不是很会,不一定对,如果有错,请指正。

youzhaing commented 2 years ago
zwmanman commented 2 years ago

class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ helper = {}

    for idx, val in enumerate(nums):
        if target - val not in helper:
            helper[val] = idx
        else:
            return [helper[target - val], idx]
ForLittleBeauty commented 2 years ago

思路


BFD+三层排序


代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
        verDict = collections.defaultdict(
            lambda: collections.defaultdict(list))
        q = collections.deque([[root,0,0]])
        while q:
            for _ in range(len(q)):
                node,col,row = q.popleft()
                verDict[col][row].append(node.val)
                if node.left:
                    q.append([node.left,col-1,row+1])
                if node.right:
                    q.append([node.right,col+1,row+1])
        result = []
        for col in sorted(verDict):
            temp = []
            for row in sorted(verDict[col]):
                temp.extend(sorted(verDict[col][row]))
            result.append(temp)
        return result

时间复杂度: O(nlogn)

空间复杂度: O(n)

tian-pengfei commented 2 years ago
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int size = nums.size();
        vector<int> re;
        for(int i=0;i<size;i++){
            int ot = findNum(target-nums[i],i+1,size,nums);
            if(ot!=-1){
               re.push_back(i);
               re.push_back(ot);
            }
        }
        return re;

    }

    int findNum(int num,int begin,int end,vector<int>& nums){

        for(int i = begin;i<end;i++){
            if(nums.at(i)==num){
                return i;
            }
        }
        return -1;
    }
};
bluetomlee commented 2 years ago
// 思路:遍历每个数字,看target-当前数字是否存在hashMap中,如果有就返回
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> hashMap;
        vector<int> res;
        for(int k = 0; k < nums.size(); k++) {
            if (hashMap.find(target - nums[k]) != hashMap.end()) {
                res.push_back(hashMap[target - nums[k]]);
                res.push_back(k);
                break;
            }
            hashMap[nums[k]] = k;
        }
        return res;
    }
};
JuliaShiweiHuang commented 2 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        numIdxSet = dict()
        i = 0
        output = []
        while (i < len(nums)):
            if (target - nums[i]) not in numIdxSet:
                numIdxSet[nums[i]] = i
            else:
                output.append(numIdxSet[target - nums[i]])
                output.append(i)
                break
            i += 1

        return output
for123s commented 2 years ago

代码

C++ Code:


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> mp;
        for(int i=0;i<nums.size();i++)
        {
            if(mp.count(target-nums[i])==1)
                return {mp[target-nums[i]],i};
            mp[nums[i]] = i;
        }
        return {};
    }
};
rockydale commented 2 years ago

思路

哈希表 遍历整数数组nums,用哈希表记录key-value,key为 target - nums[i]:目标值减去第i项的值,value为i当前下标 如果当前遍历到的nums[j]在当前哈希表中有 target - nums[j] = nums[i]的值 我们就直接从哈希表通过key为 nums[j]取出之前存的下标j,再使用当前的下标i,组成的新的数组返回。

代码

    const twoSum = function (nums, target) => {
        let map = new Map();
        for (let i = 0; i < nums.length; i++) {
            const temp = target - nums[i];
            if (map.has(temp) {
                return [map.get(temp), i];
            } else {
                map.set(nums[i], i);
            }
        }
        return [];
    }

算法复杂度

时间负责度 O(n) 空间复杂度 O(n)

nweass commented 2 years ago

思路

经典两数之和

哈希表

遍历数组,储存target - nums[i] 和下标i,如果nums[j]已经在哈希表中,说明该nums[j] = target - nums[i]

双指针

嵌套循环搜索每一个数对的和

代码

//哈希表
public int[] twoSum(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {

            if (map.containsKey(nums[i]))
                return new int[]{map.get(nums[i]), i};

            map.put(target - nums[i], i);
        }

        return new int[]{};
    }

//双指针
public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

复杂度分析

双指针

时间复杂度嵌套循环O(N^2)

空间复杂度没有使用而外空间O(1)

哈希表

时间复杂度遍历一遍O(n)

空间复杂度使用额外空间复杂度O(n)

MonkofEast commented 2 years ago

1. Two Sum

Click Me

Algo

INSIDE DNA

Code

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        adict = {}        
        for idx, n in enumerate(nums):
            if n in adict: return list((adict[n], idx))
            adict[target - n] = idx

Comp

T: O(N)

S: O(N)

Bochengwan commented 2 years ago

思路

hashmap去存已经遍历的数,然后检查下一个数需要的第二个数有没有已经出现过。

代码

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        my_dict = defaultdict()
        for i,e in enumerate(nums):
            if target-e in my_dict:
                return [my_dict[target-e],i]
            else:
                my_dict[e] = i
        return -1

复杂度分析

Alfie100 commented 2 years ago

解题思路

哈希表可降低查询的时间复杂度,当然也会同时增大空间复杂度。

Python 代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        dic = {}                            # 简历哈希表:{值:下标} 的映射
        for i, num in enumerate(nums):
            if target-num in dic:           # target-num已存在哈希表中,返回结果
                return [dic[target-num], i]
            dic[num] = i                    # 否则,加入哈希表

        return []

复杂度分析

zwx0641 commented 2 years ago

class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { if (map.get(target - nums[i]) != i) { return new int[] {i, map.get(target - nums[i])}; } } } return new int[] {}; } }

feifan-bai commented 2 years ago

思路

  1. 用hash表存储num的下标
  2. 等价于查找target-num在hash表中的值 代码
    class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = dict()
        for i, num in enumerate(nums):
            if target - num not in dic:
                dic[num] = i
            else:
                return [dic[target-num], i]

    复杂度分析

    • 时间复杂度:O(N)
    • 空间复杂度:O(N)
spacker-343 commented 2 years ago

思路

空间换时间,hash表建立值、索引的映射

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<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};
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }
}

复杂度

空间复杂度: O(n) 时间复杂度: O(n)

wenjialu commented 2 years ago

Brute : O(n^2) Iter : if res - hash[nums[I]] in history, return; else put it into hash. O(n)

code

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hash = {}
        for i in range(len(nums)):
            if target - nums[i] in hash:
                return [hash[target - nums[i]], i]
            hash[nums[i]] = i

com

Time: O(n) Space: O(n)

Laurence-try commented 2 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i in range (0, len(nums)):
            if nums[i] in dic.keys():
                return [dic.get(nums[i]), i]
            dic[target - nums[i]] = i
        return None
zhangzhengNeu commented 2 years ago

class Solution { public int[] twoSum(int[] nums, int target) { Map<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}; } map.put(nums[i], i); } return new int[]{}; } }

JudyZhou95 commented 2 years ago

思路

遍历数组,保存数字和对应index在hashmap里。每次先check target-当前数字是否已经在hashmap里,如果在就说明答案找到了。

代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_table = dict()

        for i, n in enumerate(nums):
            if target-n in num_table:
                return[num_table[target-n], i]

            num_table[n] = i

复杂度

TC: O(N)

SC: O(N)

rzhao010 commented 2 years ago

Thoughts

  1. Use hashmap, traverse array and check if target - nums[i] exists
  2. Two pointer, can be n^2 (nested loop) or nlogn (sort array and points to head&tail, but need to duplicate array and record index)

Code

public int[] twoSum(int[] nums, int target) {
        Map<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 new int[]{-1, -1};
    }

Complexity

CoreJa commented 2 years ago

思路

用哈希表构建value到index的映射,遍历列表时先看target-num是否在哈希表中,不在就将num添加到哈希表中

代码

class Solution:
    # 用哈希表构建value到index的映射,遍历列表时先看target-num是否在哈希表中,不在就将num添加到哈希表中
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = {}
        for i, num in enumerate(nums):
            if target - num not in d:
                d[num] = i
            else:
                return [i, d[target - num]]
moirobinzhang commented 2 years ago

Code:

public int[] TwoSum(int[] nums, int target) {
    if (nums == null || nums.Length == 0)
        return new int[]{};

    Dictionary<int, int> sumDicts = new Dictionary<int, int>();

    for (int  i= 0; i < nums.Length; i++)
    {
        int remainTarget = target - nums[i];

        if (sumDicts.ContainsKey(remainTarget))
            return new int[] { sumDicts[target - nums[i]], i };

        if (!sumDicts.ContainsKey(nums[i]))
            sumDicts.Add(nums[i], i);
    }        

    return new int[]{};        
}
qihang-dai commented 2 years ago
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            map.put(nums[i], i);
        }

        for(int i = 0; i < nums.length; i++){
            int sub = target - nums[i];
            if(map.containsKey(sub) && map.get(sub) != i){
                return new int[]{i, map.get(sub)};
            }
        }

        return new int[]{};

    }
}
xj-yan commented 2 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        indexDict = dict()
        for i in range(len(nums)):
            if target - nums[i] in indexDict.keys():
                return [indexDict.get(target - nums[i]), i]
            else:
                indexDict[nums[i]] = i
        return None

Time Complexity: O(n), Space Complexity: O(n)

q815101630 commented 2 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i,v in enumerate(nums):
            if target-v in dic:
                return [dic[target-v], i]
            if v not in dic:
                dic[v] = I

时空 O(n)

LinnSky commented 2 years ago

思路

js 哈希表


代码

  var twoSum = function(nums, target) {
    const hash = new Map()
    const n = nums.length
    for(let i = 0; i < n; i++){
        let match = target - nums[i]
        if(hash.has(match)) return [hash.get(match), i]
        hash.set(nums[i], i)
    }
};

复杂度分析

-时间复杂度 O(N) -空间复杂度 O(N)

Husky-Gong commented 2 years ago

Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[0] = i;
                result[1] = map.get(target - nums[i]);
            } else {
                map.put(nums[i], i);
            }
        }

        return result;
    }
}

Complexity

Time Complexity: O(N) Space Complexity: O(1)

ZhangNN2018 commented 2 years ago

思路

复杂度

代码

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        '''
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                sumij=nums[i]+nums[j]
                if sumij == target:
                    return [i,j]
XinnXuu commented 2 years ago

Code(Java)


class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<>(); 
        for (int i = 0; i < nums.length; i++) {
            if (hashtable.containsKey(target - nums[i])){
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}

Complexity

Yrtryannn commented 2 years ago
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<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};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}
wangzehan123 commented 2 years ago

Java Code:


class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] sortnums = Arrays.copyOf(nums, nums.length);
        Arrays.sort(sortnums);
        int l=0;
        int r= nums.length-1;
        boolean find =false;
        while(l<r){
            int sum = sortnums[l] + sortnums[r];
            if(sum == target){
                find =true;
                break;
            }else if(sum <target){
                l = binarySearch(sortnums, l+1, r, target-sortnums[r]);
            }else{
                r = binarySearch(sortnums, l, r-1, target-sortnums[l]);
            }
        }

        if(!find){
            return new int[0];
        }

        int[] res = new int[2];
        boolean f1=false,f2=false;
        for(int i =0 ; i<nums.length;i++){
           if(f1 && f2){
              break;   
            }
            if(!f1 && sortnums[l] == nums[i]){
                res[0]=i;
                f1=true;
                continue;
            }
            if(!f2 && sortnums[r] == nums[i]){
                res[1]=i;
                f2=true;
            }

        }
        return res;       
    }

    private int binarySearch(int[] arr, int low, int high, int target) {
        while(low < high) {
            int center = (low + high) / 2;
            if(target == arr[center]) {
                return center;
            }
            else if(target < arr[center]) {
                high = center - 1;
            }
            else {
                low = center + 1;
            }
        }
        return low;
    }
}
YuyingLiu2021 commented 2 years ago
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        # #Solution 1: 暴力求解 两个for循环
        # for i in range(len(nums)):
        #     for j in range(i+1, len(nums)):
        #         if nums[i] + nums[j] == target:
        #             return i, j
        #时间复杂度: O(N^2)
        #空间复杂度: O(1)

        # #Solution 2: Hash
        # hashset={}
        # for i in range(len(nums)):
        #     if hashset.get(target-nums[i]) is not None:
        #         return [hashset.get(target-nums[i]), i]
        #     hashset[nums[i]]=i
        #时间复杂度: O(N)
        #空间复杂度: O(N)

        #Solution 3: 排序+双指针
        temp=nums.copy()
        temp.sort()
        i=0
        j=len(nums)-1
        while i<j:
            if (temp[i] + temp[j])>target:
                j = j-1
            elif (temp[i] + temp[j])<target:
                i = i+1
            else:
                break
        p=nums.index(temp[i])
        nums.pop(p)
        k=nums.index(temp[j])
        if k>=p:
            k=k+1
        return p,k
        #时间复杂度: O(N)
        #空间复杂度: O(N)
        #not sure
zjsuper commented 2 years ago

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dic = {} for i in range(len(nums)):

        if nums[i]  in dic:
            return [dic[nums[i]],i]
        dic[target -nums[i]] = i
    return False
Alexno1no2 commented 2 years ago
#将数组元素逐个放入哈希表
#存放时,遍历到数字a,用 target 减去 a,就会得到 b,
#若 b 在哈希表中,直接返回结果
#若 b 不在哈希表中,那么将 a 存入哈希表

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        mapper = {}
        # n = len(nums)
        # for i in range(n):
        for i, num in enumerate(nums):
            if (target - num in mapper):
                return [ mapper[target - num], i ]
            else:
                mapper[num] = i
        return []
ZacheryCao commented 2 years ago

Idea

Hash Table. Use hash table to record current element's index and the result of target minus current element. The index is the value, target - element is the value. When we seen another element is in the hash table, which means current element and one element we've visited can be summed to target.

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for i in range(len(nums)):
            if nums[i] not in seen:
                seen[target - nums[i]] = i
            else:
                return [i, seen[nums[i]]]
        return []

Complexity:

Time: O(N) Space: O(N)

Hacker90 commented 2 years ago

思路

哈希表


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        cout<<nums[0]<<endl;
        unordered_map<int,int> map;
        int len = nums.size();
        for(int i = 0;i<len;i++) {
            if (map.find(target-nums[i]) != map.end()) 
                return {map[target-nums[i]],i};              
            map[nums[i]] = i;
        }

        return {};
    }
};

复杂度分析

yingliucreates commented 2 years ago
const twoSum = function(nums, target) {
    let hash = {};

    for(let i = 0; i < nums.length; i++) {
        const n = nums[i];
        if(hash[target - n] !== undefined) {
            return [hash[target - n], i];
        }
        hash[n] = i;
    }
    return [];
}
nonevsnull commented 2 years ago

思路

//s6

代码

//s6
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();

        for(int i = 0;i < nums.length;i++){
            int cur = nums[i];
            if(map.containsKey(cur)){
                return new int[]{i, map.get(cur)};
            }

            map.put(target - cur, i);
        }

        return null;
    }
}

复杂度

//use hashmap time: 需要遍历nums,O(N) space: 需要hashmap,O(N)

kite-fly6618 commented 2 years ago

思路

哈希表

代码

var twoSum = function(nums, target) {
    let len = nums.length
    let set = new Set() 
    for (let i = 0; i < len; i ++) {
        if (set.has(target-nums[i])) {
            return [nums.indexOf(target-nums[i]),i]
        }
        set.add(nums[i])
    }
};

复杂度

时间复杂度: O(n)
空间复杂度: O(n)

guoling0019 commented 2 years ago

代码

JavaScript Code:


/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums,target) {
            let map = {};
            for (let i=0;i<nums.length;i++){
                let num = nums[i];
                if((target-num) in map){
                    return [map[target-num],i]
                }else{
                    map[num] = i;
                }
            }
        }

复杂度分析

令 n 为数组长度。

Yark-yao commented 2 years ago

思路

用map存储值和下标

代码

function twoSum(nums: number[], target: number): number[] {
    // hash
    const length = nums.length
    const map = new Map()
    for(let i=0;i<length;i++){
        const need = target-nums[i]
        if(map.has(need)){
            return [
                i,map.get(need)
            ]
        }else{
            map.set(nums[i],i)
        }
    }
};

复杂度

时间:O(N) 空间: O(N)

hdyhdy commented 2 years ago

思路: 哈希表,记录见过的数的位置。

func twoSum(nums []int, target int) []int {
    ans := make(map[int]int)
    for i,k := range nums{
        if ans[k] != 0 {
            return []int{i,ans[k] - 1 }
        }else {
            ans[target-k] = i + 1
        }
    }
    return nil
}

复杂度:时间为n,空间为n

haixiaolu commented 2 years ago

思路:

哈希表,

代码 / Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = {}

        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]

            hashtable[nums[i]] = i

        return []

复杂度分析

Davont commented 2 years ago

思路

暴力 or 哈希表

code

const twoSum = function(nums, target) {
  const len = nums.length;

  // 使用哈希表存储当前值
  const map = new Map();
  for (let i = 0; i < len; i++) {
    map.set(nums[i], i);
  }

  for (let i = 0; i < len; i++) {
    const needNum = target - nums[i];

    if (map.has(needNum) && i !== map.get(needNum)) {
      return [i, map.get(needNum)]
    }
  }
}
CodingProgrammer commented 2 years ago

思路

用一个哈希表储存遍历过的值,key 为 target - nums[i],value 为 当前下标。当当前值存在哈希表的 key 中时,说明找到了匹配的一对数,那我们就把下标值填上即可

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[]{-1, -1};
        if (nums == null | nums.length == 0)
            return res;

        // target - num : index
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                res[0] = map.get(nums[i]);
                res[1] = i;
            } else {
                map.put(target - nums[i], i);
            }
        }

        return res;
    }
}

复杂度

phybrain commented 2 years ago

思路

hashmap

代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        nums_map = {}
        for i in range(len(nums)):
            n = nums[i]
            index = nums_map.get(n)
            if index is None:
                deviation = target - n
                nums_map[deviation] = i
            else:
                return [index,i]

复杂度分析