Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

给定一个数组和一个值,移除所有和这个值相等的元素,返回新数组的长度。用in-place,O(1)空间。

解法:双指针,从第一个元素开始遍历,前面的指针i指向当前数,pos指针指向交换后的元素的下一位,如果和给定的数和当前数不等就和pos元素交换,last指针右移一位,继续比较。

Java:

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

Python:

class Solution(object):
    def moveZero(self, nums, elem):
        i = 0
        for j in xrange(len(nums)):
            if nums[j] != elem:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
                
        return i  

Python:

class Solution:
    def removeElement(self, A, elem):
        i, last = 0, len(A) - 1
        while i <= last:
            if A[i] == elem:
                A[i], A[last] = A[last], A[i]
                last -= 1
            else:
                i += 1
        return last + 1

C++:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int res = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] != val) nums[res++] = nums[i];
        }
        return res;
    }
};

变形:给一个字符数组,和一个字符,删除数组中的所以给定的字符,并进行压缩。M jia

压缩就是全变成_____, eg: 数组是  abcdeba, 给的字符是 b, 删除后数组变为acdea__,后面两个是空字符

void compressMe(char[] s, char c) {
    int index = 0;
    int i = 0;
    for (; i < s.length; i++){
        if (s[i] != c){
            s[index++] = s[i];
        }
    }
    for (; index < s.length; index++){
         s[index] = ' ';
    }
}

C++:

private static void compressMe(char[] s, char c)
        {
            int insertIdx = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] != c) s[insertIdx++] = s[i];
            }

            while (insertIdx < s.Length) s[insertIdx++] = ' ';
        }

Python:  一个循环里

class Solution(object):
    def moveZero(self, nums, elem):
        i = 0
        for j in xrange(len(nums)):
            if nums[j] != elem:
                nums[i], nums[j] = nums[j], ''
                i += 1
            else:
                nums[j] = ''

类似题目:

[LeetCode] 283. Move Zeroes 移动零 

All LeetCode Questions List 题目汇总

标签智能推荐:

[LeetCode] 977. Squares of a Sorted Array 有序数组的平方值

ndyang/leetcode/issues/977类似题目:SortTransformedArrayMergeSortedArray参考资料:https://leetcode.com/problems/squares-of-a-sorted-array/https://leetcode.com/problems/squares-of-a-sorted-array/discuss/221922/J

[LeetCode] 922. Sort Array By Parity II 按奇偶排序数组之二

dyang/leetcode/issues/922类似题目:参考资料:https://leetcode.com/problems/sort-array-by-parity-ii/https://leetcode.com/problems/sort-array-by-parity-ii/discuss/181160/Java-two-pointer-one-pass-inplacehttps://l

[LeetCode] 1047. Remove All Adjacent Duplicates In String 移除字符串中所有相邻的重复字符

yang/leetcode/issues/1047类似题目:RemoveAllAdjacentDuplicatesinStringII参考资料:https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/https://leetcode.com/problems/remove-all-adjacent-duplica

[LeetCode] 948. Bag of Tokens 令牌包

};Github同步地址:https://github.com/grandyang/leetcode/issues/948参考资料:https://leetcode.com/problems/bag-of-tokens/https://leetcode.com/problems/bag-of-tokens/discuss/383249/Java-Solution-With-Explanationh

Leetcode No.160 Intersection of Two Linked Lists相交链表(c++实现)

次走两步slower=slower-&gt;next;//慢指针一次走一步if(faster==slower){//快慢指针相遇,说明存在环returntrue;}}returnfalse;//不存在环的情形}};参考:https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49789/My-accepted-s

LeetCode高频题目(100)汇总-Java实现

&nbsp;LeetCode高频题目(100)汇总-Java实现&nbsp;&nbsp;&nbsp;【Leetcode-easy-1】TwoSum【Leetcode-easy-2】AddTwoNumbers【Leetcode-easy-3】LongestSubstringWithoutRepeatingCharacters【Leetcode-easy-5】LongestPalindromicSub

[LeetCode] 1029. Two City Scheduling 两个城市调度

ps://github.com/grandyang/leetcode/issues/1029参考资料:https://leetcode.com/problems/two-city-scheduling/https://leetcode.com/problems/two-city-scheduling/discuss/278716/C%2B%2B-O(n-log-n)-sort-by-savings

8.2

python版按键精灵,pyautogui。未完成,看书deeplearning,刷题leetcode。明日:网络脚本,看书,刷题。

Leetcode练习第一题

ap.put(nums[i],i);}thrownewIllegalArgumentException("Notwosumsolution");}}作者:guanpengchn链接:https://leetcode-cn.com/problems/two-sum/solution/jie-suan-fa-1-liang-shu-zhi-he-by-guanpengchn/来源:力扣(LeetCod

2021/11/07

了!https://leetcode.com/problems/k-closest-points-to-origin/submissions/审题真的很重要!而且我觉得面试的时候最好不要作死手写quickselect了,还是老老实实用sort吧。另外,python还是不太熟悉,依然在纠结是否下决心换语言。https://leetcode.com/problems/flatten-nested-li