数组是放在连续的内存空间中的数据结构,可通过索引直接定位
因为连续,所以删除 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