LeetCode(一)Two Sum

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;
    }
}

提交后结果:

 

比较简单,内存消耗如何优化,大家可以指点一下。

posted on 2021-03-28 21:24  wishine  阅读(45)  评论(0)    收藏  举报

导航