标签:bsp hashmap twosum value contains dict leetcode return elf
本题思路是用一个key-value数据结构去保存已经遍历到的数字。
public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> hm = new HashMap<>(); for(int i =0; i<nums.length;i++){ if(hm.containsKey(target-nums[i])){ return new int[]{i,hm.get(target-nums[i])}; }else hm.put(nums[i], i); } return null; }
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: demo = dict() for idx, i in enumerate(nums): if target - i in demo: return [idx, demo[target-i]] else: demo[i] = idx
标签:bsp hashmap twosum value contains dict leetcode return elf
原文地址:https://www.cnblogs.com/huangzengrui/p/12335589.html