在开始前:
推荐安装一个插件:https://github.com/XYShaoKang/refined-leetcode 可以帮助记录做题时间,了解自己的熟练程度。
第一题
Description:
Given an array of integers
nums
which is sorted in ascending order, and an integertarget
, write a function to searchtarget
innums
. Iftarget
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数组的序号进行增加或减少,这也是二分查找的精髓。
第二题
Given an integer array
nums
and an integerval
, remove all occurrences ofval
innums
in-place. The order of the elements may be changed. Then return the number of elements innums
which are not equal toval
.Consider the number of elements in
nums
which are not equal toval
bek
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
.- 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的死循环。
第一天的题都不是很难,吃老本吃下来了。