1. Two Sum

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 the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Java

思路:
1.利用HashMap,将输入的数组和index关联,其中数组作为key,index作为value;
  • 为什么不能将index作为key,数组作为value?
  • 因为输出的是数组的index,而map只有通过key提取value的方法,即map.get(key);
2.通过for循环,既建立map,又遍历循环;

3.输出是两个数的数组,所以要创建一个数组作为return;

public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];   //创建一个数组作为return
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();   //用<type1,type2>控制类型
    for (int i = 0; i < numbers.length; i++) {  
        if (map.containsKey(target - numbers[i])) {    //是否含有此值
            result[1] = i + 1;       //此值较大,返回到后一个上
            result[0] = map.get(target - numbers[i]);   //此值较小,返回到前一个上
            return result;   //结果返回
        }
        map.put(numbers[i], i + 1);   //map添加
    }
    return result;   //结果返回
}





Python

following is python code:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        self.list = nums
        self.target = target
        for i in range(0, len(self.list)):
            for j in range(0, len(self.list)):
                if i == j:
                    pass
                else:
                    if self.target == self.list[i] +self.list[j]:
                        newlist = [i, j]
                        newlist = sorted(newlist)
        return newlist

following is python code developed:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        self.list = nums
        self.target = target
        for i in range(0, len(self.list)):
            for j in range(i+1, len(self.list)):
                if self.target == self.list[i] + self.list[j]:
                    newlist = [i, j]
        return newlist


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值