LeetCode练习之数组

414 第三大的数

Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums=sorted(list(set(nums)),reverse=True)
        return nums[2] if len(nums)>2 else nums[0]
        

88 合并两个有序数组

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        i=m-1
        j=n-1
        k=m+n-1
        while i>=0 and j>=0:
            if nums1[i]<nums2[j]:
                nums1[k]=nums2[j]
                j-=1
            else:
                nums1[k]=nums1[i]
                i-=1
            k-=1
        if j>=0:
            nums1[:(k+1)]=nums2[:(j+1)]

380 常数时间插入、删除和获取随机元素

class RandomizedSet(object):

  def __init__(self):
      """
      Initialize your data structure here.
      """
      self.randomlist=[]
      

  def insert(self, val):
      """
      Inserts a value to the set. Returns true if the set did not already contain the specified element.
      :type val: int
      :rtype: bool
      """
      if val in self.randomlist:
          return False
      else:
          self.randomlist.append(val)
          return True
      
  def remove(self, val):
      """
      Removes a value from the set. Returns true if the set contained the specified element.
      :type val: int
      :rtype: bool
      """
      if val not in self.randomlist:
          return False
      else:
          self.randomlist.remove(val)
          return True

  def getRandom(self):
      """
      Get a random element from the set.
      :rtype: int
      """
      return self.randomlist[random.randint(0,len(self.randomlist)-1)]

41 缺失的第一个正数

Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

class Solution:
    def firstMissingPositive(self, nums):
        n = len(nums)

        for i in range(n):
            if nums[i] <= 0 or nums[i] > n:
                nums[i] = n + 1
        for i in range(n):
            if abs(nums[i]) > n:
                continue
            nums[abs(nums[i]) - 1] = -abs(nums[abs(nums[i]) - 1])
        for i in range(n):
            if nums[i] > 0:
                return i + 1
        return n + 1

59 螺旋矩阵

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n 2 n^2 n2 in spiral order.

class Solution(object):
    def generateMatrix(self, n):
        i,j,di,dj=0,0,0,1
        res=[[0]*n for _ in range(n)]
        for k in range(1,n*n+1):
            res[i][j]=k
            if res[(i+di)%n][(j+dj)%n]:
                di,dj=dj,-di#顺时针,di,dj=-dj,di逆时针
            i+=di#一步一步地移动
            j+=dj
        return res

859 亲密字符串

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

For example, swapping at indices 0 and 2 in “abcd” results in “cbad”.

class Solution(object):
    def buddyStrings(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: bool
        """
        n=len(a)
        if len(b)!=n:
            return False
        if a==b:
            data=set()
            for i in a:
                if i in data:
                    return True
                data.add(i)
        else:
            index=[]
            for i in range(n):
                if a[i]!=b[i]:
                    index.append(i)
            if len(index)==2:
                if a[index[0]]==b[index[1]] and a[index[1]]==b[index[0]]:
                    return True
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值