Nuggets team number online, help you Offer impromptu! Click on theCheck the details

preface

The first time to participate in the Nuggets punch card activity, among other things, mainly rush to reward. 4.12 Start to rush to achieve the small goal of question 14!! This is problem number 11.

Topic describes

Title link: Remove element

For the title description, I mainly use the screenshot leetcode, so the title is as follows

Thought analysis

You must only use O(1) extra space and modify the input array in place.

I wanted to use splice to remove the value equal to val, and the position of the index to remove the value corresponds to that of indexOf, which felt easy to open directly.

How can it be wrong to be a little bit unexpected, and it’s going to be unexpected, and then you run it in the browser and it’s going to look like this, okay

I looked at the title again: discoveryAnd returns the new length of the removed arrayReturn the array lengthreturn nums.length, submitted as follows

Good test passed, but to be honest it’s a little misleading to say that the wrong message was submitted and it didn’t feel very friendly.

The order of the elements can be changed. You don’t have to worry about the super new length in the array and the following element gives me a new idea, which is to iterate over nums, and then use an I for the number that’s not equal to val, and then return I

So the question is, what is the NUMs now? Is the NUMs the same as the nums of the first method?

If the first method returns arr, then the second method returns arr1, which is the last half of the array nums, and returns the same length as the original array. If the second method is correct, the array order can be changed. I don’t have to worry about anything beyond the length, and that’s what inspired me to do it this way.

AC code

/** * @param {number[]} val * @return {number} */ val) { if(! nums.length){ return 0 } let index=nums.indexOf(val) while(index! =-1){ nums.splice(index,1) index = nums.indexOf(val) } return nums.length }; Var removeElement = function(nums, val) {if(! nums.length){ return 0 } let i = 0; for(let j =0; j<nums.length; j++){ if(nums[j]! =val){ nums[i]=nums[j] i++ } } return i };Copy the code

conclusion

Persistence is victory. Problem 11 algorithm complete, persistence is victory!!

Left left left

→ Algorithm series link ←

Write write write

You can order it here! You can order it here! You can order it here!