力扣学习--初级算法--Python3

数组

删除排序数组中的重复项

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if nums == None :  #非空检验
            return 0  
        else:
            c = len(nums)-1     #获取数组长度,倒序删除
            for i in range(c):
                if nums[c-i] == nums[c-i-1]:
                    del nums[c-i]
            
        return len(nums)

买卖股票的最佳时机 II

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        t = 0  #初始化最大利益
        for i in range(len(prices)-1):  #只要后一天价格高于今天就买入,后一天再卖出
            if prices[i+1] - prices[i] > 0:
                t = t + prices[i+1] - prices[i]
        
        return t

旋转数组

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        a = len(nums)-1 #获取最后一位的序号
        for i in range(k):  #先在左边插入最后一位,然后删除多出的
            nums.insert(0,nums[a])
            del nums[a+1]

存在重复元素

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
    #使用set检测关系,如果set后的数组与原来的数组长度相同则判断为无重复数组,否则为包含重复元素数组
        if len(set(nums))==len(nums):    
            return False
        else:
            return True

只出现一次的数字

class Solution:
   def singleNumber(self, nums: List[int]) -> int:
       c = 0
       for i in range(len(nums)): #使用异或来计算
           c = c ^ nums[i]
       
       return c

两个数组的交集 II

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums = [] #空数组,使用双循环查交集
        for i in range(len(nums1)):
            for j in range(len(nums2)):
                if nums1[i] == nums2[j]:
                    nums.append(nums2[j])
                    del nums2[j]
                    break
        return nums

加一

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        s = 0  #将数组合并为一个整数,然后对这个整数加1,再将整数分成数组
        l = len(digits)
        for i in range(l):
            s = s + digits[i] * pow(10,l-i-1)
        s = s + 1
        y=[]
        for i in str(s):
            y.append(int(i))
        return y

移动零

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        l = len(nums)
        for i in range(l):
            if nums[l-i-1] == 0:
                del nums[l-i-1]
                nums.append(0)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值