【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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值