LeetCode

1. Two Sum

2017-12-30  本文已影响6人  陌儿的百科全书

1.原题

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].

2.题意

给定一个整形数组,一个整形目标值,找出这个数组中两个元素的下标,这两个元素之和等于目标值。比如数组nums是[2, 7, 11, 15],目标值是9的话,那么nums[0] + nums[1]就等于9,所以返回[0, 1]

3.思路

具体做法就是:

4.代码实现

本系列的文章都会使用两种语言实现:javapython,也是笔者最近用的较多的,不排除后面会继续加入其它的语言。

java代码参见如下:

class Solution { public int[] twoSum(int[] nums, int target) { HashMap num_index = new HashMap();

        for(int i = 0; i < nums.length; i++) {

            if(num_index.containsKey(target - nums[i])) {

                return new int[] {num_index.get(target - nums[i]), i};

            }

            num_index.put(nums[i], i);

        }

        throw new IllegalArgumentException("No solution for two sum");

  }

}

python代码参见如下:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        num_index = {}
        for i in range(len(nums)):
            if target - nums[i] in num_index.keys():
                return [num_index.get(target - nums[i]), i]
            num_index[nums[i]] = i
        return []
        
上一篇下一篇

猜你喜欢

热点阅读