当前位置:网站首页>ACM Player Illustration leetcode remove element
ACM Player Illustration leetcode remove element
2022-06-23 14:21:00 【Programming Wen Qing, Li goudan】
Hello, everyone , I'm handsome .
At first, when talking about arrays, I didn't write practical problems , At that time, I thought that arrays were so simple , What's there to write about .
Until recently, some egg powder told me , I found out that it was myself xue xue Some of them are gone .
I can write a lot !
It reminds me “ The curse of knowledge ”, When a person knows something , I can't imagine what it looks like in the eyes of the unknown .
I take it as a warning .
Because arrays are so commonly used , I'll pick out several types of questions , It's about the readers in the picture .
Think of something else later and continue to add .
Today's solution Remove elements , yes Classic topic of fast and slow pointer . Don't talk much , Direct alignment .
LeetCode 27: Remove elements
The question
Give you an array nums And a val, Remove all values in place equal to val Value , And return the new length of the array after removal .
Example
Input :nums = [0,1,2,2,3,0,4,2], val = 2
Output :5, nums = [0,1,4,0,3]
explain : Function should return the new length 5, also nums The first five elements in are 0, 1, 3, 0, 4. Note that these five elements can be in any order . You don't need to think about the elements in the array that follow the new length .
Tips
You have to use O(1) Space complexity and modify the input array in place .
- 0 <= len(nums) <= 100
- 0 <= nums[i] <= 50
- 0 <= val <= 100
title
Water problem , The title is simple. .
This problem is equivalent to the deletion of array elements , Since it involves the deletion of arrays , It's not like deleting it for granted .
I'm in the article 【ACM Players take you around the array 】 In the said :
The array is made with A contiguous segment of memory space , To store the same data type A collection of data . Because of this “ Continuous memory storage ”, Make the array insert or delete elements , Other elements have to move accordingly .
The amount of data in this problem array is very small , Only... At most 100 individual , So you can use violence to crack .
The so-called violence is the most mindless way , Two layers of for loop , first floor for Cycle from 0 Start traversing array , The second floor for The element after the loop maintenance moves forward .
Like the first floor for Loop through to the subscript 2 Location found nums[2] == val, Then the second cycle will i+1 ~ n -1 All elements in position move forward one position .
Because it's double for loop , The time complexity is O(n²).
Although it can AC, But obviously, as the three good men of the new era , Ben Shuai egg's pursuit in this respect is certainly not slow , But the acme of second man , I want to hurry !
If you want me to hurry up , I have to mention Speed pointer 了 .
Speed pointer , seeing the name of a thing one thinks of its function , Is to use pointers with different speeds ( Can be used in linked lists 、 Array 、 Sequence, etc ), To solve some problems .
The speed pointer uses fast and slow Two pointers control , Quick pointer fast Point to the current and val Elements of contrast , Slow pointer slow Point to the position to be assigned :
- Traversal array .
- If fast The element that the pointer points to nums[fast] != val, be nums[fast] Is the element of the output array , Assign it to nums[slow] The location of ,slow and fast Move back one bit at the same time .
- If nums[fast] == val, Prove the present nums[fast] Is the element to be deleted ,fast Move back a bit .
- fast Traverse the entire array , end ,slow The value of is the length of the remaining array .
The illustration
With nums = [0,1,2,2,3,0,4,2], val = 2 For example .
Initialize first fast and slow The pointer .
# Initialize speed pointer fast = slow = 0
Traverse the entire array .
The first 1 Step ,fast = 0,slow = 0, here nums[fast] = 0, It's not equal to val.
here nums[slow] = nums[fast]( Although they are one now ),slow and fast Move back a bit .
# If the value pointed to by the fast pointer is not equal to val
# fast The element pointing to the position points to slow Assign a value to the position pointed to
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1The first 2 Step ,fast = 1,slow = 1, here nums[fast] = 1, It's not equal to val.
here nums[slow] = nums[fast],slow and fast Move back a bit .
The first 3 Step ,fast = 2,slow = 2, here nums[fast] = 2, be equal to val.
here fast Move back a bit ,slow Immobility .
# If the fast pointer points to a value equal to val # only fast The pointer moves , No direction slow The position pointed to by the pointer is assigned fast += 1
The first 4 Step ,fast = 3,slow = 2, here nums[fast] Is still 2, be equal to val.
So still fast Move back a bit ,slow Immobility .
The first 5 Step ,fast = 4,slow = 2, here nums[fast] = 3, It's not equal to val.
here nums[slow] = nums[fast] = 3,slow and fast Move back a bit .
The first 6 Step ,fast = 5,slow = 3,nums[fast] = 0, It's not equal to val.
here nums[slow] = nums[fast] = 0,slow and fast Move back a bit .
The first 7 Step ,fast = 6,slow = 4,nums[fast] = 4, It's not equal to val.
here nums[slow] = nums[fast] = 4,slow and fast Move back a bit .
The first 8 Step ,fast = 7,slow = 5,nums[fast] = 2, and val equal .
here fast Move back a bit ,slow unchanged , End of array traversal .
It can be seen that , here from [0, slow) For the rest of the output array ,slow The value of is the length of the remaining array .
The solution to this problem , Used a layer for loop , therefore The time complexity is O(n).
Two extra pointers are used fast and slow, The space complexity is O(1).
Code implementation
Python Code implementation
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if len(nums) == 0:
return 0
# Initialize speed pointer
fast = slow = 0
while fast < len(nums):
# If the value pointed to by the fast pointer is not equal to val
# fast The element pointing to the position points to slow Assign a value to the position pointed to
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
# If the fast pointer points to a value equal to val
# only fast The pointer moves , No direction slow The position pointed to by the pointer is assigned
fast += 1
return slowJava Code implementation
class Solution {
public int removeElement(int[] nums, int val) {
// Initialize speed pointer
int fast = 0;
int slow = 0;
for (; fast < nums.length; fast++) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
}The diagram removes elements That's the end , Array combat first article , Do you feel it ?
It's just an appetizer , The wonderful topic is still behind .
Remember to help me give the thumbs-up ah , Let me feel numb !
I'm handsome , I'll see you next time !
边栏推荐
- [deeply understand tcapulusdb technology] tmonitor module architecture
- MATLAB|时序数据中的稀疏辅助信号去噪和模式识别
- Unity realizes the function of playing Ogg format video
- SQLserver2008r2安装dts组件不成功
- 2021-04-15
- Proofs of Elsevier Elsevier Journal (Neptune Neptune) (problems encountered: latex remove the chapter number)
- KS008基于SSM的新闻发布系统
- 微信小程序之input前加图标
- 【深入理解TcaplusDB技术】如何实现Tmonitor单机安装
- Thinking and Practice on Quality Standardization (suitable for product, development, testing and management post learning)
猜你喜欢

首个大众可用PyTorch版AlphaFold2复现,哥大开源OpenFold,star量破千

Former amd chip architect roast said that the cancellation of K12 processor project was because amd counseled!
![[compréhension approfondie de la technologie tcaplusdb] données de construction tcaplusdb](/img/0c/33d9387cd7733a0c6706a73f9535f7.png)
[compréhension approfondie de la technologie tcaplusdb] données de construction tcaplusdb

Use openvinotm preprocessing API to further improve the reasoning performance of yolov5

Add Icon before input of wechat applet

微信小程序之下拉菜单场景
![[in depth understanding of tcapulusdb technology] how to realize single machine installation of tmonitor](/img/6d/8b1ac734cd95fb29e576aa3eee1b33.png)
[in depth understanding of tcapulusdb technology] how to realize single machine installation of tmonitor

Intelligent digital signage solution

Basic data types of C language and their printouts

The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
随机推荐
How does activity implement lifecycleowner?
今年英语高考,CMU用重构预训练交出134高分,大幅超越GPT3
The second Tencent light · public welfare innovation challenge was launched, and the three competition topics focused on the social value of sustainable development
【深入理解TcaplusDB技術】TcaplusDB構造數據
Test article
Wechat applet pop up the optional menu from the bottom
Oracle进入sqlplus 报错
Working for 7 years to develop my brother's career transition test: only by running hard can you get what you want~
Shell process control - 39. Special process control statements
Quartus call & design D trigger Simulation & timing wave verification
leetcode:242. Valid Letter ectopic words
Use openvinotm preprocessing API to further improve the reasoning performance of yolov5
Technology creates value and teaches you how to collect wool
MIT 6.031 reading5: version control learning experience
In depth analysis of mobilenet and its variants
Is flush a stock? Is it safe to open an account online now?
Binding events of wechat applet in wx:for
Learning experiences on how to design reusable software from three aspects: class, API and framework
[deeply understand tcapulusdb technology] tcapulusdb import data
2022 年以后,对AI开发人员意味着什么