【leetcode】两数之和&&删除排序数组中的重复项(python实现)

1.两数之和

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

我想到的是冒泡排序法遍历求和如果两数相等就返回,但是时间负责度是O(n²)

代码:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
		
        loop = len(nums)-1
        min_index = 0
       
       #总共需要比较多少次
        for i in range(loop):
            min_index += 1
            #每次需要比较多少趟
            for j in range(min_index,loop+1):
                if nums[i]+nums[j] == target:
                    return [i,j]

看了评论发现可以用字典做,时间复杂度是O(n),太强了

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

删除排序数组中的重复项

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。

题目要求不能使用额外的数组空间,只能在原数组当中进行修改并返回。

class Solution:
    def removeDuplicates(self, nums):
        if len(nums) == 0:
            return 0
        i = 1
        for l in range(1, len(nums)):
            if nums[l] == nums[l-1]:
                pass
            else:
                nums[i] = nums[l]
                i = i+1
        return i

猜你喜欢

转载自blog.csdn.net/qq_43538596/article/details/89040664