Two Sum

来源:互联网 发布:新页软件破解 编辑:程序博客网 时间:2024/05/22 09:02

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use thesame element twice.


给定一组整数,两个数字的返回索引,这样它们就会加到一个特定的目标上。
您可能假设每个输入都有一个解决方案,并且您可能不使用相同的元素两次。


Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].



JAVA

public int[] twoSum(int[] numbers, int target) {    int[] result = new int[2];    Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < numbers.length; i++) {        if (map.containsKey(target - numbers[i])) {            result[1] = i;            result[0] = map.get(target - numbers[i]);            return result;        }        map.put(numbers[i], i);    }    return result;}



PYTHON

def twoSum(self, nums, target):        d={}        for i,num in enumerate(nums):            if target-num in d:                return d[target-num]+1, i+1            d[num]=i

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 大型狗 资讯狗 好看的狗 狗和 狗的外形 狗查查 纯种狗 广联达破解版免狗 免疫组化 免疫性疾病 免疫系统 免疫性肝炎 免疫疾病 免疫球蛋白e 免疫性脑炎 风湿免疫 免疫 免疫调节药 免疫调节 体液免疫 免疫疗法 免疫细胞 免疫抑制 风湿免疫病 什么是免疫 免疫了 特异性免疫 免疫印迹 一滴血测免疫系统状况 一滴血测免疫系统状况0 破伤风免疫球蛋白 静注人免疫球蛋白ph4 免疫系统疾病 自身免疫性疾病 免疫组化什么意思 免疫缺陷病毒抗体 打免疫球蛋白后悔 破伤风免疫球蛋白多少钱一针 免疫性血小板减少症 自身免疫性脑炎 免疫球蛋白适合什么人