LeetCode OJ_题解(python):001-Two Sum 【Array】【Easy】

题目:

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.

输入一个数组和target,要在一个数组中找到两个数字,其和为target,从小到大输出数组中两个数字的位置。题目中假设有且仅有一个答案。

Example:

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

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

题目思路:

① 如果直接暴力解决,时间复杂度为(O(n^2)),两个循环,分别从数组中找到两个num,两者相加等于target。

②那么如果给定的数组是有序的会不会降低难度呢?如果是有序的数组,那么我们可以用“夹逼定理”来处理。简单来说就是首尾相加,如果比target大,则将尾数左移,如果小了首尾右移,直到两个数相加刚好等于target,那么我们可以先将数组排序,然后用双指针向中间“夹逼”,这种方法的时间复杂度为(O(nlogn)。这种方法要注意的是排序的时候要记录数组原来的位置,然后再排序。

③还有一种方法,使用字典。在python里面有一个dictionary的和C++ 的map功能一样。首先,我们建立一个字典,d = {},字典的key是数组的值num,value是相应的位置, 然后只要满足 num 和 target - num都在字典里面则找到答案。开始时字典是空的,从列表中开始读取值,当 num 和 target - num 都找到时,即停止寻找。这种方法的时间复杂度是(O(n)),不过空间复杂度是 O(MAXN)。


代码:

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        # sort
        sorted_num = sorted(num)

        # two points
        left = 0
        right = len(num) - 1
        res = []
        while (left < right):
            sum = sorted_num[left] + sorted_num[right]
            if sum == target:
                # find out index
                break;
            elif sum > target:
                right -= 1
            else:
                left += 1

        if left == right:
            return -1, -1
        else:
            pos1 = num.index(sorted_num[left]) + 1
            pos2 = num.index(sorted_num[right]) + 1
            if pos1 == pos2:    # find again
                pos2 = num[pos1:].index(sorted_num[right]) + pos1 + 1

            return min(pos1, pos2), max(pos1, pos2)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}# d is a dictionary to map the value of nums and the index in nums
        size = 0
        while size < len(nums):
            if not nums[size] in d:
                d[nums[size]] = size + 1 #if nums[size] doesn‘t exist in d ,create it
            if target - nums[size] in d: #if nums[size] and target - nums[size] are both in d
                if d[target-nums[size]] < size + 1: # one situation should be minded nums[size] == target - nums[size]
                    ans = [d[target - nums[size]] , size + 1]# for example [0,1,2] 0 and [0,1,2,0],0
                    return ans
            size = size + 1

PS:

如果想要使用pycharm进行调试,可以使用主函数(放在程序最后):

if __name__ == "__main__":
    s = Solution()
    print(s.twoSum([4, 2, 3, 6], 8))

结果:

时间: 2024-10-27 06:49:17

LeetCode OJ_题解(python):001-Two Sum 【Array】【Easy】的相关文章

LeetCode(26)题解:Remove Duplicates from Sorted Array

https://leetcode.com/problems/remove-duplicates-from-sorted-array/ Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this

LeetCode OJ_题解(python):027-Remove Element 【Array】【Easy】

题目: Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. The order of elements can be changed. It doesn't mat

LeetCode OJ_题解(python):035-Search Insert Position【Array】【Easy】

题目: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2[1,3,5,6]

【LeetCode】【Python题解】Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). Ho

【LeetCode】【Python题解】Pascal&#39;s Triangle

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 要求输入一个整数,返回一个表示杨辉三角的数组.我的方法是计算通项公式,首先是编写阶乘函数,然后计算C00,C10,C11即可 利用Python 的map嵌套可以很简洁地实现,核心代码只有一行! class So

LeetCode | 0215. Kth Largest Element in an Array数组中的第K个最大元素【Python】

LeetCode 0215. Kth Largest Element in an Array数组中的第K个最大元素[Medium][Python][快排][堆] Problem LeetCode Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1:

[leetcode]Maximum Subarray @ Python

原题地址:https://oj.leetcode.com/problems/maximum-subarray/ 题意: Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [?2,1,?3,4,?1,2,1,?5,4],the contiguous subarray [4,?1,2,

[LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 026. Remove Duplicates from Sorted Array (Easy) 链接: 题目:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ 代码(github):https://github.com/ill

LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables

最近两周一直感觉学习比较松懈, 打算加大一点强度, 从今天开始, 希望能在每天正常进度完成后在LeetCode上选一两题写一写, 同时学习一下高手的做法. LeetCode - Algorithms #001 Two Sum 给定一个整数数组, 找出其中两个元素, 使其和等于目标值, 返回这两个元素在原数组中的索引组成的数组. 可以假设有且只有一组正解, 且每个元素只能使用一次. 我的思路: 其实想不到什么好的方法, 遍历就好, 非常素朴的回答: 1 class Solution { 2 pub