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.

解法一:

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val) {
 4         if (nums.empty()) {
 5             return 0;
 6         }
 7
 8         int i = 0;
 9         int j = 0;
10         while (i < nums.size()) {
11             if (nums[i] != val) {
12                 nums[j++] = nums[i++];
13             }
14             else {
15                 ++i;
16             }
17         }
18
19         return j;
20     }
21 };

双指针

解法二:

 1 public int removeElement(int[] nums, int val) {
 2     int i = 0;
 3     for (int j = 0; j < nums.length; j++) {
 4         if (nums[j] != val) {
 5             nums[i] = nums[j];
 6             i++;
 7         }
 8     }
 9     return i;
10 }

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.

解法三:

 1 public int removeElement(int[] nums, int val) {
 2     int i = 0;
 3     int n = nums.length;
 4     while (i < n) {
 5         if (nums[i] == val) {
 6             nums[i] = nums[n - 1];
 7             // reduce array size by one
 8             n--;
 9         } else {
10             i++;
11         }
12     }
13     return n;
14 }

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.

时间: 2024-10-24 07:47:12

27. Remove Element【easy】的相关文章

27. Remove Element【leetcode】

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

Leet Code OJ 27. Remove Element [Difficulty: Easy]

题目: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 翻译: 给定一个数组和一个值,在原地移除所有的这个值的实例,并且返回新的数组长度. 元素的顺序可以被改变.

LeetCode:27. Remove Element(Easy)

1. 原题链接 https://leetcode.com/problems/remove-element/description/ 2. 题目要求 给定一个整数数组 nums[ ] 和一个整数 val,删除数组中与val相同的元素,并返回删除后的数组长度 注意:不能定义新的数组,只能使用O(1)空间大小 3. 解题思路 遍历一次,将每个元素与给定的value进行比较,不同则给nums[count++]赋予当前元素的值:相同则直接跳过,最后返回count,即为删除后数组的长度. 4. 代码实现 p

26. Remove Duplicates from Sorted Array【easy】

26. Remove Duplicates from Sorted Array[easy] Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with consta

680. Valid Palindrome II【easy】

680. Valid Palindrome II[easy] Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You co

661. Image Smoother【easy】

661. Image Smoother[easy] Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself.

605. Can Place Flowers【easy】

605. Can Place Flowers[easy] Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die. Given a flowerbed (represe

1. Two Sum【easy】

1. Two Sum[easy] Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums

189. Rotate Array【easy】

189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note:Try to come up as many solutions as you can, there are at least 3 differen