数组类27--删除指定元素(E)

2019-08-15  本文已影响0人  干LeetCode

给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素

AC代码:

import java.util.Arrays;
class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums == null || nums.length < 1) {
            return 0;
        }
        Arrays.sort(nums);
        int step = 0;
        int firstIndex = -1;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == val) {
                if(firstIndex == -1) {
                    firstIndex = i;
                }
                step++;
            }
        }
        if(firstIndex == -1) {
            return nums.length;
        }
        if(firstIndex + step == nums.length) {
            return firstIndex;
        }
        for(int i = firstIndex + step; i < nums.length; i++) {
            nums[i - step] = nums[i];
        }
        return nums.length - step;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读