LeetCode经典面试150题-day2(移除元素)

1、题目

LeetCode经典面试150题-day2(移除元素)_第1张图片

2、分析

⑴ 、遍历数组,每个值和指定元素做比较

⑵ 、移除指定元素,可以理解为挑出不同元素

⑶ 、取数组中的值赋给新数组,并记录次数 

⑷ 、返回记录次数就是新数组的长度

3、解题

LeetCode经典面试150题-day2(移除元素)_第2张图片

    /**
     * 移除元素
     *
     * @param nums
     * @param val
     * @return
     */
    public static int removeElement(int[] nums, int val) {
        int size = nums.length;
        int tempIndex = 0;
        for (int i = 0; i < size; i++) {
            if (nums[i] != val) {
                nums[tempIndex] = nums[i];
                tempIndex++;
            }
        }
        return tempIndex;
    }

你可能感兴趣的:(leetcode,面试,算法)