LeetCode第一题:Two Sum,
题目:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
非常简单,就不做解释了,show me the code:
class Solution { public int[] twoSum(int[] nums, int target) { int[] ret = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int first = nums[i]; int second = target - first; if (map.containsKey(second)) { ret[0] = map.get(second); ret[1] = i; return ret; } else { map.put(nums[i], i); } } return ret; } }
提交后结果:
比较简单,内存消耗如何优化,大家可以指点一下。
原文:https://www.cnblogs.com/wishine/p/14590065.html