leetcode 27. Remove Element

题目

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
    assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.

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.
It does not matter what you leave beyond the returned k (hence they are underscores).

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.
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).

Constraints:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100

题目分析

这个leetcode真的是
昨天写的
今天写复盘笔记思路就能忘…

我认为刷编程题和刷数学题一样
看了五分钟想不到思路就直接看答案学习即可
对于一个算法如果最开始就学习了最优解
那么次解就不需要学习了
直接都是优解开路
培养优解思维
为什么还要一直沉浸于次解的自我欣赏里面
难道只是因为次解是自己想出来的好像有思考价值吗

数组移除元素是一个很常见的场景
可以用c++中的erase-remove函数很简单的实现

但是使用双指针解法就好像 两个人分工 一个人清点 另一个人执行
一个指针顺序检查是不是符合数值条件 发现不符合另一个指针直接配合执行覆盖操作
但与此同时随着被覆盖的数值本身也占了一个位置 顺序检查的指针只会停留在和目标值不同的位置上 如果发现相同则直接跳过 这时候配合执行的指针还在原地 也就产生了速度快慢的差异
所以一个跑得快的负责检查的指针叫fast指针
另一个配合执行的指针叫slow指针

slow指针每一次向前移动 都伴随着合法元素的归位 掌握着新数组的元素顺序
fast指针像一个士兵一样剔除旧的不合法元素

双指针移动解法

class solution{
public:
int removeElement(vector<int>& nums, int val) {
		int slow = 0;
		for(int fast = 0; fast < nums.size(); fast++)
		{
			if(nums[fast] != val)
			{
				nums[slow++] = nums[fast];
			}
		}
		length = slow;
		return length;
	}
}
  • 21
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Every DAV inci

小辣鸡一枚,不求打赏啦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值