代码随想录算法训练营Day 1 | 数组 (1/2) Leetcode704. 二分查找,27. 移除元素

在开始前:

推荐安装一个插件:https://github.com/XYShaoKang/refined-leetcode   可以帮助记录做题时间,了解自己的熟练程度。

第一题

1.  LeetCode 704 Binary search

Description: 

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.

看到题的初步想法就是使用二分查找,用时4分40秒,代码如下:

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums)-1
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                l = mid + 1
            elif nums[mid] > target:
                r = mid - 1
        return -1

由于给定数组是ascending order,因此在elif中,可以在比较和target的大小后,直接对nums数组的序号进行增加或减少,这也是二分查找的精髓。

第二题

2. LeetCode 27 remove element

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

请注意:

in-place algorithm is an algorithm that operates directly on the input data structure without requiring extra space proportional to the input size. In other words, it modifies the input in place, without creating a separate copy of the data structure. An algorithm which is not in-place is sometimes called not-in-place or out-of-place

由于要求是in place,因此不能考虑额外的空间,只能使用交换等操作。

这道题我使用了双指针,一头一尾。只要左指针比右指针小,就会一直进行如下操作:

  • 如果头指针指的数字不等于目标,就头指针往后走一位
  • 如果头指针是要的数,且尾指针不是要的数,那就头尾指针指向的数交换(如果尾指针指向的也是目标数,那交换位置就没意义了),然后头指针往后一位,尾指针往前一位
  • 如果都不满足(比如头指针的数是目标数,或者头和尾指针都是目标数),那就尾指针往前一位

用时11分46秒

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i ,j = 0 ,len(nums) - 1
        while i <= j:
            if nums[i] != val:
                i += 1
            elif nums[i] == val and nums[j] != val:
                nums[i] , nums[j] = nums[j],nums[i]
                i +=1
                j -= 1
            else:
                j -=1
        return i

注意,双指针解题的时候,每一个if、elif里都别忘了让某一个指针移动一下,不然会造成while的死循环。

第一天的题都不是很难,吃老本吃下来了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值