Leetcode刷题记录本

Liang's Blog / 2023-08-09 / 原文

Leetcode刷题记录本

ID: 1

  1. 暴力破解法
点击查看代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
		# 暴力破解法
        for i in range(len(nums)):
            for j in range(len(nums)):
                if nums[i]+nums[j]==target:
                    return [i,j]
  1. 使用字典,即key-map
点击查看代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        records = dict()
        for index,value in enumerate(nums):
            if target-value in records:
                return [records[target-value],index]
            records[value] = index

ID: 704

  • 二分查找
点击查看代码
class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left, right = 0,len(nums)-1
        while left<=right:
            mid = (left+right)//2
            if nums[mid]<target:
                left = mid+1
            elif nums[mid]>target:
                right = mid-1
            else:
                return mid
        return -1

ID: 27

  • 快慢指针
点击查看代码
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        fast=slow=0
        n = len(nums)
        for fast, value in enumerate(nums):
            if nums[fast]!=val:
                nums[slow] = nums[fast]
                slow+=1
        return slow