LeetCode0-Two Sum-[Easy]

羞于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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容