数组理论基础
【重点1】:数组是存放在连续内存空间上的相同类型数据的集合。
- 数组下标从0开始
- 数组的内存空间是连续的
【重点2】:删除数组元素
可以理解为,数组的元素是不能删的,只能覆盖。
【重点三】: 二维数组
- 什么是二维数组:
- 二维数组在内存的空间地址是连续的么?
C++中,二维数组的排列是连续的
Java中,二维数组的排列是不连续的,排列方式如下图
数组总结
LeetCode 704. Binary Search
很经典的题,依然是一看就会,一写就废···
视频连接:B站:二分查找
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.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104
-104 < nums[i], target < 104
- All the integers in
nums
are unique. nums
is sorted in ascending order.
方法:使用[左闭右闭] 规则
此时,left <= right,因为left = right是有意义的;
mid = nums[right] - 1 或者 mid = nums[left] + 1
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
mid = 0
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
# if the nums do not have the target value, return -1
return -1
遇到的报错
- 在计算mid时,没有使用//,使用了/
//
和/
的区别
// 取的是结果的最小整数,而 / 取得是实际的除法结果
LeetCode 27. Remove Element
第一次做这道题~
视频连接:B站:移除元素
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. Return k
as the length of the output nums
.
Example 1:
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.
Example 2:
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.
方法:双指针(快慢指针法)
双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组、链表、字符串等操作的面试题,都使用双指针法。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
slow = 0
fast = 0
while fast <= len(nums)-1:
if nums[fast] != val:
# slow pointer point to the removal, it will be coverd by the value of fast pointer
nums[slow] = nums [fast]
slow += 1
# fast pointer will move forward by 1 step anyway
fast += 1
# finally, reuturn the slow pointer which is eqaul to the size of the new nums
return slow
遇到的报错
浅浅的理解后,半抄半写吧····没有什么报错
这道题还需继续努力····
Summary
- 数组的内存地址是连续的,下标从0开始
- 数组是不可以被删除的,只能被覆盖
- 二维数组的内存地址在C++中是连续的,在Java中是不连续的
//
的结果是小的整数,/
的结果是准确值- LeetCode 27题要重新做!!!