当前位置:网站首页>Lexicon 27 - Remove Elements - Simple Questions

Lexicon 27 - Remove Elements - Simple Questions

2022-08-02 11:46:00 Zhang Ran Ran √

Title description

Given an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.

Don't use extra array space, you must use only O(1) extra space and modify the input array in place.

The order of the

elements can be changed.You don't need to consider elements in the array beyond the new length.

Description:

Why is the returned value an integer, but the output answer is an array?

Please note that the input array is passed "by reference", which means that modifications to the input array within the function are visible to the caller.

Solution ideas

The original intention of this question is to return an array that excludes val. The main idea is as follows:

  • traverse the array nums;
  • If the element is not the same as val, it does not need to be processed, if it is the same as val, then nums[i] needs to be removed;
  • Returns the maximum number of indices for the last nums.

Input and output example

Code

class Solution {public int removeElement(int[] nums, int val) {int len ​​= nums.length;int num = 0;for(int i = 0; i < len; i++){if(nums[i] != val){nums[num] = nums[i];num++;}}return num;}}

原网站

版权声明
本文为[Zhang Ran Ran √]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208021141359339.html