LeetCode027——移除元素

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82413748

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/remove-element/description/

题目描述:

知识点:数组、双指针

思路:一个指针从前往后遍历数组,另一个指针记录不等于val的值

本题的题目描述和解题思路几乎都与LeetCode026——删除排序数组中的重复项一模一样,不同的是我们要删除的不再是重复项,而是值和val相等的元素,其实更简单了。

第一个指针从前往后遍历数组,第二个指针记录值不为val的元素。

整个过程只遍历了一次数组,时间复杂度是O(n),其中n为nums数组的长度。修改数组是在原数组上进行的,空间复杂度是O(1)。

JAVA代码:

public class Solution {
	
	public static int removeElement(int[] nums, int val) {
		int index = 0;
		for(int i = 0; i < nums.length; i++) {
			if(nums[i] == val) {
				continue;
			}
			nums[index] = nums[i];
			index++;
		}
		return index;
	}
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82413748