二分查找和删除元素

这篇博客探讨了数组数据结构的特性,强调了其在内存中的连续存储方式以及如何通过索引快速访问元素。文章首先介绍了二分查找算法,给出一个在有序数组中查找目标值的示例,实现了O(logn)的时间复杂度。接着,讨论了数组在删除或增加元素时可能需要移动其他元素的问题,指出数组不能直接删除元素但可以通过覆盖实现删除。最后,展示了如何在数组中移除指定元素,同时保持原数组空间不变,返回新数组的有效长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数组是放在连续的内存空间中的数据结构,可通过索引直接定位

因为连续,所以删除 or 增加元素的时候有可能需要移动其他元素

所以数组不能删除,可以用覆盖进而删除

704:二分查找

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

  • Input: nums = [-1,0,3,5,9,12], target = 9
  • Output: 4
  • Explanation: 9 exists in nums and its index is 4
def Binary_search(nums, target):
    i = 0
    j = len(nums) - 1
    while i <= j:
        mid = (i + j) // 2
        if nums[mid] < target:
            i = mid + 1
        elif nums[mid] > target:
            j = mid - 1
        else:
            return mid
    return -1
Binary_search([-1,0,3,5,9,12], 9)
4

27:移除元素

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

  • Input: nums = [3,2,2,3], val = 3

  • Output: 2, nums = [2,2,,]

  • Explanation: Your function should return k = 2, with the first two elements of nums being 2.

  • It does not matter what you leave beyond the returned k (hence they are underscores).

  • Input: nums = [0,1,2,2,3,0,4,2], val = 2

  • Output: 5, nums = [0,1,4,0,3,,,_]

  • Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.

  • Note that the five elements can be returned in any order.

  • It does not matter what you leave beyond the returned k (hence they are underscores).

def removeElement(nums, val):
    i = 0
    for j in range(len(nums)):
        if nums[j] != val:
            nums[i] = nums[j]
            i += 1
    return i
removeElement([0,1,2,2,3,0,4,2],2)
5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值