美文网首页Leetcode程序员
LeetCode0-Two Sum-[Easy]

LeetCode0-Two Sum-[Easy]

作者: 殷大侠 | 来源:发表于2017-05-12 17:30 被阅读41次

羞于post,但勇于丢脸。
本系列将记录渣渣成长之路,目的主要为个人的刷题思路总结。
目前默认language:Python。

题目Description:Two Sum

Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.
You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].

思路1:

遍历加和。

class Solution(object):
    def twoSum(self, nums, target):
        a = 0;
        while (a < len(nums) ):
            for x in nums:
                for y in nums:
                    result = x + y
                    if (result == target ) & (nums.index(x) <> nums.index(y)):
                        return (nums.index(x),nums.index(y))
                        a = a + 1

结果:Time Limit Exceeded

思路2:

参考思路3的方法,遍历索引。

class Solution(object):
   def twoSum(self, nums, target):
           for x in range(len(nums)):
               if target - nums[x] in nums:
                   if x <> nums.index(target - nums[x]):
                       return [x,nums.index(target - nums[x])]

思路3:(参考solution,来源如图)

我当前还没搞懂这个答案……

/**
 * 本代码由九章算法编辑提供。版权所有,转发请注明出处。
 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,Big Data 项目实战班,
 * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
 */

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
         numbers=[2, 7, 11, 15],  target=9
         return [1, 2]
     */
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer,Integer> map = new HashMap<>();

        for (int i = 0; i < numbers.length; i++) {
            if (map.get(numbers[i]) != null) {
                int[] result = {map.get(numbers[i]) + 1, i + 1};
                return result;
            }
            map.put(target - numbers[i], i);
        }
        
        int[] result = {};
        return result;
    }
}

相关文章

网友评论

    本文标题:LeetCode0-Two Sum-[Easy]

    本文链接:https://www.haomeiwen.com/subject/xgqtxxtx.html