python实现leetcode算法题库-twoSum-两数之和(1)

给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 的那两个整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
class TwoSum:
    """
    nums: [int]
    target: int
    return: two ele's index, [int]
    """
    def __init__(self, nums, target):
        self.nums = nums
        self.target = target

    def demo_On2(self):
        """
        O(n^2)
        :return:
        """
        for i in range(len(self.nums)):
            for j in range(i+1, len(self.nums)):
                if self.nums[i] + self.nums[j] == self.target:
                    return [i, j]
        return []

    def demo_Onlogn(self):
        """
        O(nlogn)
        :return:
        """
        # sorted_id >>> list consist of every ele's index in the nums
        sorted_id = sorted(range(len(self.nums)), key= lambda k:self.nums[k])
        print(sorted_id)
        head = 0
        tail = len(self.nums) - 1
        sum_res = self.nums[sorted_id[head]] + self.nums[sorted_id[tail]]
        while sum_res != target:
            if sum_res > target:
                tail -= 1
            elif sum_res < target:
                head += 1

            sum_res = self.nums[sorted_id[head]] + self.nums[sorted_id[tail]]
        return  [sorted_id[head], sorted_id[tail]]

    def demo_On(self):
        """
        O(n)
        :return:
        """
        dict_ = {}
        # enumerate >>> generator obj
        for index, num in enumerate(nums):
            other_num = self.target - num
            if other_num in dict_:
                return [dict_[other_num], index]
            # key >>> num, index >>> value
            dict_[num] = index

        return None




if __name__ == "__main__":
    nums = [1, 3, 8, 2, 8, 5]
    target = 16
    twoSum = TwoSum(nums, target)
    res = twoSum.demo_On()
    print(res)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

上一篇:“21天好习惯”第一期——17


下一篇:shell 函数返回值