27. Remove Element【easy】
27. Remove Element【easy】
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
解法一:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if (nums.empty()) {
return ;
}
int i = ;
int j = ;
while (i < nums.size()) {
if (nums[i] != val) {
nums[j++] = nums[i++];
}
else {
++i;
}
}
return j;
}
};
双指针
解法二:
public int removeElement(int[] nums, int val) {
int i = ;
for (int j = ; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
Intuition
Since question asked us to remove all elements of the given value in-place, we have to handle it with O(1) extra space.
How to solve it? We can keep two pointers i and j, where i is the slow-runner while j is the fast-runner.
Algorithm
When nums[j] equals to the given value, skip this element by incrementing j. As long as nums[j]≠val, we copy nums[j] to nums[i] and increment both indexes at the same time.
Repeat the process until j reaches the end of the array and the new length is i.
解法三:
public int removeElement(int[] nums, int val) {
int i = ;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - ];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
Intuition
Now consider cases where the array contains few elements to remove. For example, nums = [1,2,3,5,4], val = 4.
The previous algorithm will do unnecessary copy operation of the first four elements. Another example is nums = [4,1,2,3,5], val = 4.
It seems unnecessary to move elements [1,2,3,5]one step left as the problem description mentions that the order of elements could be changed.
Algorithm
When we encounter nums[i] = val, we can swap the current element out with the last element and dispose the last one. This essentially reduces the array's size by 1.
Note that the last element that was swapped in could be the value you want to remove itself. But don't worry, in the next iteration we will still check this element.
27. Remove Element【easy】的更多相关文章
- 27. Remove Element【leetcode】
27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...
- LeetCode:27. Remove Element(Easy)
1. 原题链接 https://leetcode.com/problems/remove-element/description/ 2. 题目要求 给定一个整数数组 nums[ ] 和一个整数 val ...
- 83. Remove Duplicates from Sorted List【easy】
83. Remove Duplicates from Sorted List[easy] Given a sorted linked list, delete all duplicates such ...
- 26. Remove Duplicates from Sorted Array【easy】
26. Remove Duplicates from Sorted Array[easy] Given a sorted array, remove the duplicates in place s ...
- 203. Remove Linked List Elements【easy】
203. Remove Linked List Elements[easy] Remove all elements from a linked list of integers that have ...
- 121. Best Time to Buy and Sell Stock【easy】
121. Best Time to Buy and Sell Stock[easy] Say you have an array for which the ith element is the pr ...
- 448. Find All Numbers Disappeared in an Array【easy】
448. Find All Numbers Disappeared in an Array[easy] Given an array of integers where 1 ≤ a[i] ≤ n (n ...
- 1. Two Sum【easy】
1. Two Sum[easy] Given an array of integers, return indices of the two numbers such that they add up ...
- 167. Two Sum II - Input array is sorted【easy】
167. Two Sum II - Input array is sorted[easy] Given an array of integers that is already sorted in a ...
随机推荐
- 静态NAT地址转换
1.配置路由器端口ip(两个端口需要设置两个网段) Router(config)#inter f0/1 Router(confiog-if)#ip add 202.1.1.2 255.255.255. ...
- python内建datetime模块
datetime 获取当前日期和时间 from datetime import datetime now = datetime.now() print(now) datetime转换为timestam ...
- [转][译] 分分钟学会一门语言之 Python 篇
Python was created by Guido Van Rossum in the early 90's. It is now one of the most popularlanguages ...
- Klaus Aschenbrenner--windbg
http://www.sqlservercentral.com/blogs/aschenbrenner/?page=1
- Java使用纯真IP库获取IP对应省份和城市
原文:http://blog.csdn.net/chwshuang/article/details/78027873?locationNum=10&fps=1 Java使用纯真IP库获取IP对 ...
- isNaN使用的注意事项
NaN是JavaScript的特殊值,表示 Not a Number 用法: isNaN(numValue); 如果值是 NaN, 那么 isNaN 函数返回 true ,否则返回 false . 注 ...
- Intellij IDEA System.out.println输出中文乱码问题
进行下列设置即可:
- lykops运维自动化
lykops lykops是一套web可视化的运维自动化项目,基于python3+django开发的. 已实现功能 1.用户管理 详情 2.主机管理 主要功能:收录主机,为其他模块(例如:执行任务)直 ...
- 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:3.安装Oracle RAC-3.3.安装前检查
3.3. 安装前检查 1.检查节点连通性 或:./runcluvfy.sh stage -pre crsinst -n linuxrac1,linuxrac2 -fixup -verbose [gri ...
- java压缩 GZIP进行简单压缩,ZIP进行多文件保存
java压缩 GZIP进行简单压缩,ZIP进行多文件保存 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGlhbmdydWkxOTg4/font/5a6 ...