美文网首页
[Leetcode] Remove Element 删除数组元素

[Leetcode] Remove Element 删除数组元素

作者: 高思阳 | 来源:发表于2018-10-18 13:44 被阅读0次

    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.
    双指针法
    复杂度
    时间 O(N) 空间 O(1)
    思路
    用一个指针记录不含给定数字的数组边界,另一个指针记录当前遍历到的数组位置。只有不等于给定数字的数,才会被拷贝到子数组的边界上。
    代码
    public class Solution {
    public int removeElement(int[] nums, int val) {
    int pos = 0;
    for(int i = 0; i < nums.length; i++){
    // 只拷贝非给定数字的元素
    if(nums[i] != val){
    nums[pos] = nums[i];
    pos++;
    }
    }
    return pos;
    }
    }
    交换法
    复杂度
    时间 O(N) 空间 O(1)
    思路
    因为题目中并不要求相对顺序保持一致,所以有进一步优化的空间。我们遍历数组时,每遇到一个目标数,就和当前数组结尾交换,并把数组大小减1,如果不是目标数,则检查下一个数字。这样可以减少很多赋值操作。
    代码

    public class Solution {
    public int removeElement(int[] nums, int val) {
    int size = nums.length, i = 0;
    while(i < size){
    if(nums[i] == val){
    swap(nums, i, size - 1);
    size--;
    } else {
    i++;
    }
    }
    return size;
    }

    private void swap(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    

    }

    相关文章

      网友评论

          本文标题:[Leetcode] Remove Element 删除数组元素

          本文链接:https://www.haomeiwen.com/subject/fmnjzftx.html