zoukankan      html  css  js  c++  java
  • 【leetcode】Two Sum

    题目简述:

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    解题思想:

    首先我很是不甘心的直接暴力了一次,果断TLE。然后想到先排序,然后两个指针前后搜,大了就后面的指针前移,小了就前面的指针后移。不过比较麻烦的是要找出原来的位置,导致代码多了几个丑陋的循环。

    #coding=utf-8
    class Solution:
        # @return a tuple, (index1, index2)
        def twoSum(self, num, target):
            t = []
            for i in num:
                t.append(i)
            num.sort()
            l = len(num)
            index1 = 0
            index2 = l-1
            while index1 < index2:
                if num[index1] + num[index2] == target:
                    break
                elif num[index1] + num[index2] > target:
                    index2 -= 1
                elif num[index1] + num[index2] < target:
                    index1 += 1
            for i in range(l):
                if num[index1] == t[i]:
                    index1 = i
                    break
            for i in range(l):        
                if num[index2] == t[i] and i != index1:
                    index2 = i
                    break
            if index1 >index2:
                return index2+1,index1+1
            return index1+1,index2+1
    

    不过后来看到的标准解法里用了哈希表,We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index。于是就用dict写了下,不过可能是python的dict比较慢还是怎么,速度几乎一样,不过代码倒是短了不少。

    class Solution:
        # @return a tuple, (index1, index2)
        def twoSum(self, num, target):
            t = {}
            l = len(num)
            for i in range(l):
                t[num[i]] = i
            for i in range(l):
                if t.has_key(target-num[i]):
                    if i != t[target-num[i]]:
                        return i+1 , t[target-num[i]]+1
  • 相关阅读:
    Eclipse代码快捷键
    QuickBI助你成为分析师——计算字段功能
    怎么从Linux服务器上下载超过4G的文件?
    centOS7下Spark安装配置
    s3c2440裸机-清bss原理及实现
    s3c2440裸机-代码重定位(2.编程实现代码重定位)
    Markdown语法教程
    s3c2440裸机-代码重定位(1.重定位的引入,为什么要代码重定位)
    s3c2440裸机-内存控制器(五、SDRAM编程实现)
    s3c2440裸机-内存控制器(四、SDRAM原理-cpu是如何访问sdram的)
  • 原文地址:https://www.cnblogs.com/MrLJC/p/4229875.html
Copyright © 2011-2022 走看看