高编作业(七)

本文介绍了解决两个经典算法问题的方法:一是去除有序数组中的重复元素并返回新长度;二是找出目标值在一个已排序数组中的起始和结束位置。

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

题目:26. Remove Duplicates from Sorted Array

题目描述

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

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

解题思路

只需要找array[i]=array[i+1]的项,然后把array[i+1]项删除,循环一次就好。

代码

    def removeDuplicates(self, nums):
        if len(nums)<=0:
            return 0
        key, i = nums[0], 1
        while i<len(nums):
            if nums[i]==key:
                nums.pop(i)
            else:
                key = nums[i]
                i += 1
        return len(nums)

AC截图

这里写图片描述

题目:34. Search for a Range

题目描述

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

解题思路

先用二分查找,在列表中找到target(若找不到则返回[-1,-1])
每一次查找都记录上一次查找的区间[left, right],当找到target之后(此时区间一定满足nums[left]<=target,nums[right]>=target,且所有target一定在这个区间里)
然后这个区间的左边自增,右边自减,直至nums[left]=nums[right]=target为止
最终得到的[left,right]即为所求

代码

def searchRange(self, nums, target):
    if len(nums)<=0:
            return [-1, -1]
        uleft, uright = 0, len(nums)
        left, right = 0, len(nums)
        mid, flag = 0, 1
        while True:
            mid = (left + right)//2
            if mid<len(nums) and nums[mid]==target:
                break
            if left == right or mid>=len(nums):
                return [-1, -1]
            if nums[mid]<target:
                uleft = left
                left = mid + 1
            else:
                uright = right
                right = mid
        uright -= 1
        while uleft<mid or uright>mid:
            if nums[uleft] == target and nums[uright]==target:
                break
            if nums[uleft]<target and uleft<mid:
                uleft += 1
            if nums[uright]>target and uright>mid:
                uright -= 1
        return [uleft, uright]

AC截图

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值