Python处理数组常用技巧

Python 双指针 删除有序数组中重复元素

利用双指针fast 和 slow 删除有序数组的重复元素。返回slow, 说明nums中有slow个不同的元素。代码如下:

class Solution:
    def removeDuplicatesFromList(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 0:
            return 0
        else:
            slow = 1
            for fast in range(len(nums)):
                if fast > 0 and nums[fast] != nums[fast-1]:
                    nums[slow] = nums[fast]
                    slow = slow + 1
            return slow

Python 二分法查找有序数组

class Solution:
    def searchInsert(self, nums: list[int], target: int) -> int:
        left , right = 0, len(nums)-1
        while left <= right:
            mid = int(left + (right-left)/2)
            if target == nums[mid]:
                return mid
            elif target > nums[mid]:
                left = mid+1
            else:
                right = mid-1
        return left

Python 二维数组用+拼接成一维

m = [['2', '1', '1'], ['3', '3'], ['4']]
a = []
for i in m:
    a =a + i
print(a)

运行结果如下:

['2', '1', '1', '3', '3', '4']

Python 异或

from functools import reduce


def singleNumber(nums: list[int]) -> int:
    return reduce(lambda x, y: x ^ y, nums)


print(singleNumber([2, 3, 2, 3, 1, 4, 4]))

输出结果如下:

1

你可能感兴趣的:(测试开发,python,leetcode,排序算法)