首页 > 其他 > 详细

LeetCode(一)Two Sum

时间:2021-03-29 00:11:55      阅读:39      评论:0      收藏:0      [点我收藏+]

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

提交后结果:

技术分享图片

 

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

LeetCode(一)Two Sum

原文:https://www.cnblogs.com/wishine/p/14590065.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!