当前位置:网站首页>leetcode 数组类
leetcode 数组类
2022-07-26 19:58:00 【Yuki_1999】
704题:二分查找
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
二分查找
1)条件:元素有序,无重复元素
2)过程:假设表中元素升序排列,中间位置元素与查找元素比较,相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
class Solution(object):
def search(self, nums, target):
left,right=0,len(nums)-1
while left<=right:
middle=(right-left)//2
if target>nums[middle]:
left=middle+1
elif target<nums[middle]:
right=middle-1
else:
return middle
return -1
27题:移除元素
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
双指针法(快慢指针法)
1)定义:快指针指向当前要处理的元素,慢指针指向下一个要赋值的位置
2)使用场合:很多考察数组、链表、字符串等操作的面试题,都使用双指针法。
class Solution(object):
def removeElement(self, nums, val):
left=0
for right in range(0,len(nums)):
#不相等则在原数组上覆盖
if nums[right]!=val:
nums[left]=nums[right]
left+=1
return left
边栏推荐
- 营销与销售文件管理以及工作流程解决方案
- Houdini notes 2
- Shell综合应用案例,归档文件
- Pandonia spirit voxedit creation competition
- Buu brush inscription 4
- The typing competition is over!
- QT driving school subject examination system -- from implementation to release
- Installation and configuration of [basic services] [database] Clickhouse
- Leetcode-300 longest increasing subsequence
- Gartner released the latest market guide for Chinese AI start-ups, and Hongji cyclone was once again rated as a representative enterprise
猜你喜欢

Depthwiseseparableconvolution: depthwise convolution and pointwise convolution

Houdini notes 2

How to implement an asynchronous task queue system that can handle massive data (supreme Collection Edition)

Buu brush inscription 2

What are the advantages of digital factory

Experiment 5 OSPF comprehensive experiment

Execution context and Lexical Environment

BGP routing black hole and anti ring

ST表、带权并查集

APP自动化测试框架搭建(八)--ATX Server2多设备集群环境搭建
随机推荐
BUU刷题记4
Fitting the new direction of curriculum standards, ape guidance, creating a characteristic new concept content system
LCP 11. Statistics of expected number
Quick start to connection pooling
Summary of message queue knowledge points
李彦宏遭“泼冷水”热情不减!百度结盟华为麒麟,发布“鸿鹄”芯片
The typing competition is over!
South Korea plans to spend 1 trillion won a year on research and development of semiconductor materials and equipment
Gbase learning - install gbase 8A MPP cluster v95
[record of question brushing] 22. bracket generation
深度可分离卷积(DepthwiseSeparableConvolution):Depthwise卷积与Pointwise卷积
Build Prometheus automatic monitoring and alarm system from scratch
查询字段较多时可以添加普通查询和高级查询两种情况
HM中如何获取CU块划分信息并用Matlab绘图
Gartner released the latest market guide for Chinese AI start-ups, and Hongji cyclone was once again rated as a representative enterprise
20220726
The UK and Germany have successively launched 5g commercial services, and Huawei has become a behind the scenes hero
The lawyer team of the US Department of justice asked the judge to refuse to accept Huawei's lawsuit
What are the advantages of digital factory
[基础服务] [数据库] ClickHouse的安装和配置