leetcode 练习

1.从排序数组中删除重复项

class Solution(object):
  def removeDuplicates(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    length=len(nums)
    if length==0:
    return 0
    i=0
    for j in range(1,length):
      if nums[j]!=nums[i]:
        i+=1
        nums[i]=nums[j]

    return i+1

2.买卖股票的最佳时机 II

class Solution(object):
  def maxProfit(self, prices):
    """
    :type prices: List[int]
    :rtype: int
    ""''

    profit = 0

    for i in range(1,len(prices)):
      if prices[i] > prices[i-1]:
        profit += prices[i]-prices[i-1]
    return profit

3.给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数

思路1

class Solution(object):
  def rotate(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: None Do not return anything, modify nums in-place instead.
    """
    i=0
    j=0
    length=len(nums)
    while i<k:
      n=nums[-1]
      for j in range(0,length-1):
        nums[len(nums)-j-1]=nums[len(nums)-j-2]
        nums[0]=n
        i=i+1
    return nums

思路2

class Solution:
  def rotate(self, nums, k):
    nums_len = len(nums)
    nums[:] = nums[nums_len - k :] + nums[:nums_len - k] #数组切片可以直接加减,放在一起
    print(nums)

4.存在重复

class Solution(object):
  def containsDuplicate(self, nums):
    """
    :type nums: List[int]
    :rtype: bool
    """
    dict = {}
    for i in nums:
      if dict.get(i):
        return True
      dict[i] = 1
    return False

5.只出现一次的数字

这个想法是看别人的,精彩。

class Solution(object):
  def singleNumber(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    result = 0
    for num in nums:
      result = result ^ num
    return result

猜你喜欢

转载自www.cnblogs.com/lt230/p/10455810.html