两数相加
给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]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};}else{map.put(nums[i], i);}}return null;}}利用map集合同时存储数值与序号。逐步循环,检验已录入的值是否可以符合两数相加和,满足则输出两数序号。不满足则将当期值存入map中。
